//-------------------------------------------------------//
// Author:Rodolfo Machon
// Company:WebSoft, SA de CV 
// Nombre del archivo: mandamientos_qmd.js
// Created: 2016-08-04
// Updates: 2016-08-04
// Copyright - All Rights Reserved
//-------------------------------------------------------//
//-------------------------------------------------------//
weekdays 	= new Array("Domingo", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado");
months 		= new Array("Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre");
var isIE    = document.all?true:false;
var isNS    = document.layers?true:false;
var xmlHttp10; 
var xmlHttpStream10;
var xmlHttp11; 
var xmlHttpStream11;
var xmlHttp12; 
var xmlHttpStream12;
var xmlHttp13; 
var xmlHttpStream13;
var xmlHttp2;
var xmlHttpStream2;
var xmlHttp3;
var xmlHttpStream3;
var xmlHttp4;
var xmlHttpStream4;
//-------------------------------------------------------//
window.onload = function(){

};
//-------------------------------------------------------//
//LEVEL 1
function processRecibo() {
    document.getElementById('process').style.display = 'none';
    document.getElementById('print').style.display = 'none';
    document.getElementById('mandamiento').style.display = 'none';    

    window.print();
    
    if(document.form.dt_cuota.value===""){document.form.dt_cuota.value=document.form.dt_emision.value;}

    getReciboActual();
    
}
function onReciboSaved(){
    getRecibosPagos();
    getExpedienteAbonos();
    comparePagosAbonos();
    saveAbonos();
}
function ProcessPage(){
    AddCantidad();
    AddConcepto();
    AddPeriodos();
    ShowCuotaPendiente();    
    //GetUltimoRecibo();
    CambiarVencimiento(document.form.dt_emision.value);
    //GetCuentasContables();
    getExpedienteNIS();
    myFunction();
    myFunction1();
   // myFunction2();    
}
function LoadClase(target_id_field){
	var lan		  = parent.list.document.data.lan.value;
	var appid	  = parent.list.document.data.appid.value;
	var clase	  = parent.list.document.data.clase.value;
	var id 		  = parent.list.document.detail.id_field.value;
	var target_id = eval("parent.form.document.form."+target_id_field+".value");
    //alert(target_id_field+"<>"+target_id);
	if(id!="" && target_id!=""){
        var ins = 0;
        var sv  = parent.list.document.detail.dsv.value.split("~~");
        for (var i=1;i<sv.length;i++){
            var txt     = eval("document.form.txt_periodos__"+i+".value");
            if(txt!==""){
                ins++;
            }
        }
        if (ins>0) {
            InsertAbono();
        }else{
            parent.close();
        }
	}
}
function ShowSuccesfull(){

}
function Process(){
	var c16_factura		= "";
	var AxmlHttpStream	= xmlHttpStream.split("|");
	if (AxmlHttpStream[0]==""){alert("Recibos no asignados a este cajero");return}
	parent.form.document.all.process.style.visibility='hidden';
	SystemPrintPreview(6);
	parent.form.document.all.process.style.visibility='visible';	
	var ok = confirm("Se imprimio la Factura Correctamente?");
	if(ok!=true){
	    var ok1 = confirm("Desea Intentar nuevamente?");
	    if(ok1==true){
		SystemPrintPreview(OLECMDID)
	    }else{
		parent.window.close();
	    }
	}else{
	    var new_stream	= "";
	    var serie		= AxmlHttpStream[0];
	    var correlativo	= AxmlHttpStream[1];
	    var digits	 	= correlativo.length;
	    var new_count	= (correlativo*1)+1;
	    var new_stream   	= padleft(new_count,"0",digits)
	    var invoice 	= serie+"-"+new_stream;
	    do{
            c16_factura = prompt("Introduzca el numero del Recibo ISAM",invoice);
            c16_factura = c16_factura.toUpperCase();
            var ok2 	= confirm("El Numero de ISAM que Digito es:"+c16_factura+"?");
	    }while (ok2==false)
            if(ok2==true){
            document.form.c16_recibo_id.value = c16_factura;
            Save();
	    }
	}	
}
//-------------------------------------------------------//
//LEVEL 2
function getReciboActual(){
	var appid = document.form.appid.value;
    var caja  = document.form.i2_cajero_id.value;
    var cajero= document.form.i8_user_id.value;    
    var URL     = "/pl/recibo.actual.get.pl?appid="+appid+"&i2_cajero_id="+caja+"&i8_user_id="+cajero;
    //alert(URL);
    xmlHttp10	= GetXmlHttpObject(getReciboActualSC);
    xmlHttp10.open("GET",URL,true) ;
    xmlHttp10.send(null);
}
function getReciboActualSC(){
    if (xmlHttp10.readyState==4 || xmlHttp10.readyState=="complete"){ 
        xmlHttpStream10=xmlHttp10.responseText;
        //alert(xmlHttpStream10);
        var numero_a = xmlHttpStream10.split("|");
        if (numero_a[1]==""){
            alert("Recibos no asignados a este cajero");
            return;
        }else{
            var rec_cor 	= numero_a[1].replace(/\D/g,'');
            var longitud    = rec_cor.length;
            var nrec_cor	= (rec_cor*1)+1;
            var nrec_num    = zeroPad(nrec_cor,longitud);
            var nrec_id     = numero_a[0]+"-"+nrec_num;
            document.form.recibo_libro.value = nrec_id;
            document.getElementById("recibo_libro").focus();
            document.getElementById("recibo_libro").select();
            document.getElementById('rcrd_div').style.display = 'inline'; 
        }
    } 
}
function saveRecibo(){
    document.getElementById('rcrd_div').style.display = 'none'; 
	var appid	  = document.form.appid.value;
	var recibo_id = document.form.recibo_libro.value;
    var URL     = "/pl/recibo.id.check.pl?appid="+appid+"&c16_recibo_id="+recibo_id;
    //alert(URL);
    xmlHttp11	= GetXmlHttpObject(saveReciboSC);
    xmlHttp11.open("GET",URL,true) ;
    xmlHttp11.send(null);
}
function saveReciboSC(){
    if (xmlHttp11.readyState==4 || xmlHttp11.readyState=="complete"){
        var recibo_id = document.form.recibo_libro.value;
        if (recibo_id===xmlHttp11.responseText) {
            alert("El Numero de Recibo Ya Existe, Favor Ingrese Otro Numero");
            document.getElementById('rcrd_div').style.display = 'inline';             
        }else{

            var parent  = document.getElementById("ttab1");
            var child   = document.getElementById("t111");
            
           // var parent1 = document.getElementById("ccab1");
            //var child1  = document.getElementById("t112");
            
            parent.removeChild(child);
            //parent1.removeChild(child1);
            
            document.form.c16_recibo_id.value =  recibo_id;
            document.form.disabled            = true;            

            Save();            
        }
    } 
}
function AddCantidad(){
    document.form.cantidad.value=chequeAmount(document.form.subtotal__foot.value);
}
function AddConcepto(){
    var Concept = document.form.txt_concepto.value;
    var TConcep = document.getElementById('concepto');
    var NewRow  = TConcep.insertRow(1);
    var Cell       = NewRow.insertCell(0);
    Cell.innerHTML = Concept;
}
function AddPeriodos(){
    var NewHTML = "";
    var OldHTML = document.getElementById('concepto').rows[1].cells;
    var sv  = parent.list.document.detail.dsv.value.split("~~");
    for (var i=1;i<sv.length;i++){
        var TipoAbono   = "";
        var TipoPago    = "";        
        var Pers	= "";
        var txt   	= eval("document.form.txt_periodos__"+i+".value");
	if(txt!=""){
	    var txt_members = txt.split("~");
	    for(var j=0;j<txt_members.length;j++){    
		var members = txt_members[j].split(",");
		Pers+= members[0]+",";
                TipoAbono = members[7];
	    }
	    var Desc = eval("document.form.v128_tarifa__"+i+".value");
	    var Code = eval("document.form.c16_tarifa_id__"+i+".value");
            //alert(Pers);
	    var PerLabel = ConstructPeriods(Pers);
            if(TipoAbono=="P"){TipoPago="Abono "}
            if(TipoAbono=="C"){TipoPago=" "}            
	    NewHTML += Desc+"&nbsp;&nbsp;-&nbsp;&nbsp;<br>"+TipoPago+PerLabel+"<br>";
	}    
    }
    OldHTML[0].innerHTML = OldHTML[0].innerHTML+"<br>"+NewHTML;
}
function ShowCuotaPendiente(){
    var desde 	= "";
    var hasta 	= "";
    var valor   = 0;
    var sv  	= parent.list.document.detail.dsv.value.split("~~");
    var Concept = document.form.txt_concepto.value;    
	Concept 	= Concept.replace(/REMESA CAESS DEL /g,"");
	Concept 	= Concept.replace(/ /g,"");
	var fecs	= Concept.split("HASTA");
	desde		= fecs[0];
	hasta		= fecs[1];
    for (var i=1;i<sv.length;i++){
        var tari	= eval("document.form.c16_tarifa_id__"+i+".value");
		var tari_val= eval("document.form.d82_tarifa__"+i+".value");
		var tari_can= eval("document.form.d82_cantidad__"+i+".value");
		if(tari=="TSINMCUPNNAEF001"){
			valor	= tari_can*tari_val;
		}
		if(tari=="TSINMOTRNNAEF001"){
			valor	+= tari_can*tari_val;
		}		
    }
    if(valor>0 && desde !="" && hasta !=""){
		GetCuotasPendientes(desde,hasta,valor);
    }
}
function GetCuotasPendientes(d,h,v){
    var lan	= parent.list.document.data.lan.value; 
    var appid	= parent.list.document.data.appid.value; 
    var URL  = "/pl/get_cuotas_pendientes.pl?lan="+lan+"&appid="+appid+"&dt_desde="+d+"&dt_hasta="+h+"&valor="+v;
	//alert(URL);
    xmlHttp4 = GetXmlHttpObject(stateChangedGetCuotasPendientes);
    xmlHttp4.open("GET",URL,true) ;
    xmlHttp4.send(null);
}
function stateChangedGetCuotasPendientes(){
    var OldHTML = document.getElementById('concepto').rows[1].cells;	
    if (xmlHttp4.readyState==4 || xmlHttp4.readyState=="complete"){ 
        xmlHttpStream4=xmlHttp4.responseText;
        //alert("stateChangedGetCuotasPendientes =>"+xmlHttpStream4);
        OldHTML[0].innerHTML = OldHTML[0].innerHTML+"<br>"+xmlHttpStream4;
    } 
}
function InsertAbono(){
    var lan	        = parent.list.document.data.lan.value;    
    var appid	    = parent.list.document.data.appid.value;
    var clase	    = parent.list.document.data.clase.value;
    var expediente  = document.form.i8_expediente_id.value;
    var dt_abono    = document.form.dt_emision.value;
    var recibo	    = document.form.c16_recibo_id.value;
    var generador   = document.form.v64_tipo_generador.value;
    var user_id     = document.form.i8_user_id.value;
    var cajero_id   = document.form.i8_cajero_id.value;
    var emisor_id   = document.form.i8_emisor_id.value;
    var id_field    = "i8_"+generador+"_id";
    var table	    = "sdd_"+generador+"_abonos";
    var astream     = "";
    var tributo	    = "";
    var sv  = parent.list.document.detail.dsv.value.split("~~");
    for (var i=1;i<sv.length;i++){
        var txt     = eval("document.form.txt_periodos__"+i+".value");
        if(txt!=""){
            var txt_members = txt.split("~");
            for(var j=0;j<txt_members.length;j++){    
                var BalType     = "A";
                var accesorios	= txt_members[j].split(",");
                var periodo	    = accesorios[0];		
                var dias_mora	= accesorios[1];
                var tarifa	    = accesorios[2];
                var valor	    = accesorios[3];		
                var fiestas	    = accesorios[4];
                var intereses	= accesorios[5];
                var multa	    = accesorios[6];
                var tipobalance = accesorios[7];
                if(tipobalance=="P"||tipobalance=="C"){BalType="S"}
                astream += expediente+"|"+tributo+"|"+tarifa+"|"+periodo+"|"+dt_abono+"|"+dias_mora+"|DIM|"+recibo+"|IS|AMLL|CENTRAL|"+BalType+"|~~";		
                astream += expediente+"|"+tributo+"|"+tarifa+"|"+periodo+"|"+dt_abono+"|"+valor+"|VAL|"+recibo+"|IS|AMLL|CENTRAL|"+BalType+"|~~";
                astream += expediente+"|"+tributo+"|"+tarifa+"|"+periodo+"|"+dt_abono+"|"+fiestas+"|FIE|"+recibo+"|IS|AMLL|CENTRAL|"+BalType+"|~~";
                astream += expediente+"|"+tributo+"|"+tarifa+"|"+periodo+"|"+dt_abono+"|"+intereses+"|INT|"+recibo+"|IS|AMLL|CENTRAL|"+BalType+"|~~";
                astream += expediente+"|"+tributo+"|"+tarifa+"|"+periodo+"|"+dt_abono+"|"+multa+"|MUL|"+recibo+"|IS|AMLL|CENTRAL|"+BalType+"|~~";
            }	
        }    
    }
    var dif	    = id_field+",c8_tributo_id,c16_tarifa_id,i8_periodo,dt_abono,d82_abono,c3_tipo_abono_id,c16_recibo_id,c2_tipo_recibo_id,v64_abono_agencia,v64_abono_sucursal,c1_balance_type,ts_in";
    var str	    = "lan="+lan+"&appid="+appid+"&clase="+clase+"&table="+table+"&dif="+dif+"&div="+astream;
    var URL	    = "/pl/expediente.abonos.insert.pl";
    //alert(URL+"<>"+str)
    xmlHttp2	= GetXmlHttpObject(stateChangedInsertAbono);
    xmlHttp2.open("POST",URL,true);
	xmlHttp2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    
    xmlHttp2.send(str);
}
function stateChangedInsertAbono(){
    if (xmlHttp2.readyState==4 || xmlHttp2.readyState=="complete"){ 
        xmlHttpStream2=xmlHttp2.responseText;
        //alert(xmlHttpStream2);
        parent.close();
    } 
}
function CambiarVencimiento(value){
	var Members 	= value.split("-");
	var NewDate	= new Date(Members[0],Members[1]-1,Members[2]);
	var NewString	= (String(weekdays[NewDate.getDay()]))+" "+(String(NewDate.getDate()))+" DE "+(String(months[NewDate.getMonth()]))+", "+(String(NewDate.getFullYear()));
	document.form.fecha_emision.value = NewString.toUpperCase();
}
function GetCuentasContables(){
    var appid	= parent.list.document.data.appid.value;
    var str	    = "appid="+appid+"&tarifas="+parent.list.document.detail.dsv.value;
    var URL     = "/pl/get_cuentas_contables.pl";
    xmlHttp3	= GetXmlHttpObject(stateChangedGetCuentasContables);
    xmlHttp3.open("POST",URL,true) ;
    xmlHttp3.send(str);
}
function stateChangedGetCuentasContables(){
    if (xmlHttp3.readyState==4 || xmlHttp3.readyState=="complete"){ 
        xmlHttpStream3=xmlHttp3.responseText;
        //alert("stateChangedGetCuentasContables =>"+xmlHttpStream3);
    } 
}
function CopiarDatos(){   
    var dt=parent.list.document.detail.dlv.value.split("~~");
    var x=dt.length;
    for (var i=1;i<x;i++) {
        var c=dt[i-1].split("|");
        if((c[1]*1)>0) {
            eval("document.form.c16_cuenta_recurso_id__"+i+".value="+c[1]);
        }
    }
}
function getUserCajaDepartamento(){
    var URL     = "../pl/user.caja.departamento.get.pl?appid=LaUnion&lan=es";
    xmlHttp12	= GetXmlHttpObject(getUserCajaDepartamentoSC);
    xmlHttp12.open("GET",URL,true) ;
    xmlHttp12.send(null);
}
function getUserCajaDepartamentoSC(){
    if (xmlHttp12.readyState==4 || xmlHttp12.readyState=="complete"){ 
        xmlHttpStream12=xmlHttp12.responseText;
		if (xmlHttpStream12!=="false" && xmlHttpStream12!==""){
			var datos=xmlHttpStream12.split("|");
            document.form.i8_user_id.value          = datos[0];
            document.form.i8_cajero_id.value	    = datos[0];
            document.form.v16_login_cajero.value	= datos[6];
		}
    }
}
function getExpedienteNIS(){
    var exp_id  = document.form.i8_expediente_id.value;
    if (exp_id=="") {return}
    var URL     = "../pl/expediente.nis.get.pl?appid=LaUnion&lan=es&i8_expediente_id="+exp_id;
    xmlHttp13	= GetXmlHttpObject(getExpedienteNISSC);
    xmlHttp13.open("GET",URL,true) ;
    xmlHttp13.send(null);
}
function getExpedienteNISSC(){
    if (xmlHttp13.readyState==4 || xmlHttp13.readyState=="complete"){ 
        xmlHttpStream13=xmlHttp13.responseText;
        document.form.i8_nis_id.value = xmlHttpStream13;
    }
}
//-------------------------------------------------------//
// AUXILIAR
function zeroPad(num, places) {
  var zero = places - num.toString().length + 1;
  return Array(+(zero > 0 && zero)).join("0") + num;
}
function onlyDigits(e,decReq) {
    var key = (isIE) ? window.event.keyCode : e.which;
    var obj = (isIE) ? event.srcElement : e.target;
    var isNum = (key > 47 && key < 58) ? true:false;
    var dotOK = (key==46 && decReq=='decOK' && (obj.value.indexOf(".")<0 || obj.value.length==0)) ? true:false;
    window.event.keyCode = (!isNum && !dotOK && isIE) ? 0:key;
    e.which = (!isNum && !dotOK && isNS) ? 0:key;
    return (isNum || dotOK);
}
function noRet(e,decReq) {
	var key = (isIE) ? window.event.keyCode : e.which;
	var obj = (isIE) ? event.srcElement : e.target;
	var isRet = (key==13 || key=="35" || key=="34" || key=="126" || key=="124") ? false:true;
	window.event.keyCode = (!isRet && isIE) ? 0:key;
	return (isRet);
}
function padleft(val, ch, num) {
    var re  = new RegExp(".{" + num + "}$");
    var pad = "";
    do  {
        pad += ch;
    }while(pad.length < num)
        return re.exec(pad + val);
}
function padright(val, ch, num){
    var re  = new RegExp("^.{" + num + "}");
    var pad = "";
    do {
        pad += ch;
    } while (pad.length < num)
    return re.exec(val + pad);
}
function myFunction() {
    document.form.contribuyente.value        = document.form.v128_contribuyente.value;
    document.form.expediente_id.value        = document.form.i8_expediente_id.value;
    document.form.expediente_direccion.value = document.form.txt_expediente_direccion.value;
    document.form.cantidad1.value            = document.form.cantidad.value;
    document.getElementById('monto').innerHTML = putThousandsSeparators(document.form.subtotal__foot.value);
    //document.form.v16_login_emisor1.value    = document.form.v16_login_emisor.value;
    //document.form.v16_login_cajero1.value    = document.form.v16_login_cajero.value;
}
function myFunction1() {
    var cnt = document.getElementById('contribuyente');
    var tcnt= cnt.cloneNode(true);
    tcnt.id = "tcnt11";
    var ubi = document.getElementById('ubicacion');
    var tubi= ubi.cloneNode(true);
    tubi.id = "tubi11";
    var emi = document.getElementById('emision');
    var temi= emi.cloneNode(true);
    temi.id = "temi11";
    var exp = document.getElementById('expediente');
    var texp= exp.cloneNode(true);
    texp.id = "text11";   
    var tab = document.getElementById('t1');
    var con = document.getElementById('concepto');
    var con1= con.cloneNode(true);
    var tab1= tab.cloneNode(true);
    tab1.id = "t111";
    rows = tab1.rows;
    for (var j = 0; j < rows.length; j++) {
        if (rows[j].cells[3].firstChild.value == "") {
            tab1.deleteRow(j);
        }
    }
    for (var j = 0; j < rows.length; j++) {
        if (rows[j].cells[3].firstChild.value == "") {
            tab1.deleteRow(j);
        }
    }
    for (var j = 0; j < rows.length; j++) {
        if (rows[j].cells[3].firstChild.value == "") {
            tab1.deleteRow(j);
        }
    }
    
    document.getElementById("tcnt1").appendChild(tcnt)    
    document.getElementById("tubi1").appendChild(tubi)    
    document.getElementById("temi1").appendChild(temi)
    document.getElementById("texp1").appendChild(texp)    
    document.getElementById("ttab1").appendChild(tab1)
    document.getElementById("tcon1").appendChild(con1)    
}
function myFunction2() {
    var cnt = document.getElementById('contribuyente');
    var ccnt= cnt.cloneNode(true);
    ccnt.id = "ccnt11";
    var ubi = document.getElementById('ubicacion');
    var cubi= ubi.cloneNode(true);
    cubi.id = "cubi11";
    var emi = document.getElementById('emision');
    var cemi= emi.cloneNode(true);
    cemi.id = "cemi11";
    var exp = document.getElementById('expediente');
    var cexp= exp.cloneNode(true);
    cexp.id = "cext11";   
    var cab = document.getElementById('t1');
    var con = document.getElementById('concepto');
    var con1= con.cloneNode(true);
    var cab1= cab.cloneNode(true);
    cab1.id = "t112";
    rows = cab1.rows;
   
    //for (var j = 0; j < rows.length; j++) {rows[j].deleteCell(6);}
    //for (var j = 0; j < rows.length; j++) {rows[j].deleteCell(3);}
    //for (var j = 0; j < rows.length; j++) {rows[j].deleteCell(1);}
    
    document.getElementById("ccnt1").appendChild(ccnt)    
    document.getElementById("cubi1").appendChild(cubi)    
    document.getElementById("cemi1").appendChild(cemi)
    document.getElementById("cexp1").appendChild(cexp)    
    document.getElementById("ccab1").appendChild(cab1)
    document.getElementById("ccon1").appendChild(con1)    
}
var putThousandsSeparators;

putThousandsSeparators = function(value, sep) {
  if (sep == null) {
    sep = ',';
  }
  // check if it needs formatting
  if (value.toString() === value.toLocaleString()) {
    // split decimals
    var parts = value.toString().split('.')
    // format whole numbers
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, sep);
    // put them back together
    value = parts[1] ? parts.join('.') : parts[0];
  } else {
    value = value.toLocaleString();
  }
  return value;
};