//-------------------------------------------------------//
// Author:Rodolfo Machon
// Company:WebSoft, SA de CV 
// Nombre del archivo: financiamiento.plan.calc.js
// Created: 2016-07-17
// Updates: 2016-07-17;2018-06-13
// Copyright - All Rights Reserved
//-------------------------------------------------------//
//-------------------------------------------------------//
var xmlHttp;
var xmlHttpStream;
var xmlHttp1;
var xmlHttpStream1;
var openwindow;
var RowCount= 0;
var isIE    = document.all?true:false;
var isNS    = document.layers?true:false;
var lan	    = document.form.lan.value;
var appid	= document.form.appid.value;
var clase   = document.form.clase.value;
var id      = document.form.id.value;
var multaMinima = 2.86;
//-------------------------------------------------------//
window.onload = function(){
	window.resizeTo(1124,640);
}
//-------------------------------------------------------//
function GetXmlHttpObject(handler){
	var objXmlHttp=null;	
	if(window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
		objXmlHttp = new XMLHttpRequest();
		objXmlHttp.onload=handler;
		objXmlHttp.onerror=handler; 		
	}
	if(window.ActiveXObject){// code for IE6, IE5
		objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		objXmlHttp.onreadystatechange=handler;
	}
	if(objXmlHttp===null){alert("Your Browser Does Not Suppport AJAX");}
	return objXmlHttp;
}
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 Add(){
    var dtd 	= "";
    var dth 	= "";
    var pds 	= "";
	var mor		= "";
	var cor		= "";
	var tot		= "";
    var dtv     = document.form.dt_vencimiento.value;
	var tip_cuo	= document.form.tipo_cuota.value;
	var cuo_val	= document.form.d82_cuota.value;    
    var car_cor = document.form.cargo_corriente.value;
    var icc  	= document.form.incluir_cc.value;
    var venci 	= dtv.split("-");
    var ymd   	= venci[0]+venci[1]+venci[2];
	if (cuo_val>0 && tip_cuo=='FIJA') {
		if(icc=="SI"){tot=cuo_val;mor=tot-car_cor;cor=car_cor}else{tot=cuo_val;mor=cuo_val;cor=0}
		if(document.form.cuotas.value!='CALCULAR'){
			document.all.guardar_div.style.visibility='visible';
			document.all.generar_div.style.visibility='hidden';   			
		}
    }
    if(RowCount >= document.form.cuotas.value){alert("Ya supero las cuotas especificadas");return}
    if(CheckIfExist(ymd,dtv)){alert("Fecha Vencimiento Ya Existe");return}
    AddRow(dtv,ymd,pds,dtd,dth,mor,cor,tot);
    Clean('dt_vencimiento','d82_cuota');
 }
function CheckIfExist(ymd,dtv){
    var T1	= document.getElementById('t1');
    var rows	= T1.getElementsByTagName('tr');
    var Exist	= false;
    var vper_val= "";    
    for(var i=1;i<rows.length;i++){
	var vper     = "v_"+ymd;
	if(eval("document.form."+vper)){vper_val = eval("document.form."+vper+".value");}
	if(vper_val==dtv){Exist = true;return Exist;}
    }
    return Exist;
}
function AddRow(dtv,ymd,pds,dtd,dth,mor,cor,tot){
    var T1	= document.getElementById('t1');
    var lineas	= T1.getElementsByTagName('tr');	
    var count   = lineas.length;
    var NewRow	= T1.insertRow(count);
    var Cell0 	= NewRow.insertCell(0);
    var Cell1 	= NewRow.insertCell(1);
    var Cell2 	= NewRow.insertCell(2);
    var Cell3 	= NewRow.insertCell(3);
    var Cell4 	= NewRow.insertCell(4);
    var Cell5 	= NewRow.insertCell(5);
    var Cell6 	= NewRow.insertCell(6);
    var Cell7 	= NewRow.insertCell(7);
    var Cell8 	= NewRow.insertCell(8);
    var Cell9 	= NewRow.insertCell(9);
    var Cel20 	= NewRow.insertCell(10);
    var Cel21 	= NewRow.insertCell(11);
    var Cel22 	= NewRow.insertCell(12);
    var Cel23 	= NewRow.insertCell(13);
    var Cel24 	= NewRow.insertCell(14);
    var Cel25 	= NewRow.insertCell(15);
    Cell0.innerHTML = "<input type=text name=a"+(count-1)+" size=1 maxlength=2 class=my_style readonly value="+(count-1)+">";
    Cell1.innerHTML = "<input type=text name=v_"+ymd+" size=10 maxlength=10 class=my_style value="+dtv+">";
    Cell2.innerHTML = "<input type=text name=pds_"+(count-1)+" size=4 maxlength=4 class=my_style value="+pds+">";
    Cell3.innerHTML = "<input type=text name=desde_"+(count-1)+" size=10 maxlength=10 class=my_style value="+dtd+">";
    Cell4.innerHTML = "<input type=text name=hasta_"+(count-1)+" size=10 maxlength=10 class=my_style value="+dth+">";
    Cell5.innerHTML = "<input type=text name=mora_tasas_"+(count-1)+" size=8 maxlength=10 class=my_style value=''>";
    Cell6.innerHTML = "<input type=text name=mora_fiestas_"+(count-1)+" size=8 maxlength=10 class=my_style value=''>";
    Cell7.innerHTML = "<input type=text name=mora_intereses_"+(count-1)+" size=8 maxlength=10 class=my_style value=''>";
    Cell8.innerHTML = "<input type=text name=mora_multas_"+(count-1)+" size=8 maxlength=10 class=my_style value=''>";
    Cell9.innerHTML = "<input type=text name=mora_multa_minima_"+(count-1)+" size=8 maxlength=10 class=my_style value=''><input name=chk_"+(count-1)+" id=chk_"+(count-1)+" class=checkbox onclick=evalMulta('"+(count-1)+"') type=checkbox>";
    Cel20.innerHTML = "<input type=text name=mora_total_"+(count-1)+" size=8 maxlength=10 class=my_style value=''>";
    Cel21.innerHTML = "<input type=text name=corriente_tasas_"+(count-1)+" size=8 maxlength=10 class=my_style value=''>";
    Cel22.innerHTML = "<input type=text name=corriente_fiestas_"+(count-1)+" size=8 maxlength=10 class=my_style value=''>";
    Cel23.innerHTML = "<input type=text name=corriente_total_"+(count-1)+" size=8 maxlength=10 class=my_style value=''>";	
    Cel24.innerHTML = "<input type=text name=total_"+(count-1)+" size=9 maxlength=10 class=my_style value=''>";
    Cel25.innerHTML = "<input type=button value=Borrar class=button2 onclick=DeleteRow(this.parentNode.parentNode.rowIndex)>"
    RowCount++;
}
function DeleteRow(i){
    document.getElementById('t1').deleteRow(i);
    RowCount--;
}
function Clean(a,b){
    eval("document.form."+a+".value=''");
    eval("document.form."+b+".value=''");
}
function getFinanciamientoFechas(){
	//alert();
    var clase   	= "inmueble";
    var inicial 	= document.form.dt_inicial_plan.value;
    var cuo			= document.form.cuotas[document.form.cuotas.selectedIndex].value;
	var tip_cuo		= document.form.tipo_cuota.value;
	var val_cuo		= document.form.d82_cuota.value;
	var mon_ven		= document.form.monto_vencido.value;
	var car_cor		= document.form.cargo_corriente.value;
	if (tip_cuo==='VARIABLE' && cuo===0) {alert("Solo se permite CALCULAR el numero de cuotas, cuando el tipo de cuata es FIJA");return;}
	if (tip_cuo==='FIJA' && cuo===0) {
		if (val_cuo>0) {
			var val_apl = val_cuo-car_cor;
			var num_cuo = Math.ceil(mon_ven/val_apl);
			document.form.cuotas[document.form.cuotas.selectedIndex].value=num_cuo;
			cuo = num_cuo;
		}else{
			alert("Ingreso el Monto de la Cuota");
			return;
		}
	}
	if(inicial===""){alert("Favor Ingresar Fecha Inicial");return;}
	if(cuo<1){alert("Utilice Esta Opcion para Planes con Mas de 4 Cuotas");return;}
	var URL	= "../pl/financiamiento.fechas.get.pl?lan="+lan+"&appid="+appid+"&id="+id+"&clase="+clase+"&dt_inicial="+inicial+"&cuotas="+cuo;
	//alert(URL);
    xmlHttp	= GetXmlHttpObject(getFinanciamientoFechasSC);
    xmlHttp.open("GET",URL,true) ;
    xmlHttp.send(null);
}
function getFinanciamientoFechasSC(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
        xmlHttpStream=xmlHttp.responseText;
		//alert(xmlHttpStream);
				if(xmlHttpStream!==""){
	CompletarFechas(xmlHttpStream);
				}
    }
}
function getFinanciamientoPlan(){
    var cuo	   		= document.form.cuotas[document.form.cuotas.selectedIndex].value;
    var periodos_v 	= document.form.periodos_vencidos.value;
    var mora_desde 	= document.form.dt_desde.value;
    var mora_hasta 	= document.form.dt_hasta.value;
    var incFiestas	= document.form.fiestas.value;
    var incInteres	= document.form.intereses.value;
    var incMultas	= document.form.multas.value;
    var incCorriente= document.form.incluir_cc.value;
	var corTasas	= document.form.d82_tasa.value;
	var corFiestas	= document.form.d82_fiesta.value;
	var corTotal	= document.form.cargo_corriente.value;
    var T  	   		= document.getElementById('t1');
    var trows 	   	= T.rows;
    var expe	   	= "";
    for(var i=2;i<trows.length;i++){
		var x = T.rows[i].cells[1].getElementsByTagName("input");
		expe += x[0].value.replace(/-/g,"")+"|";
    }
    if(expe===0){alert("Favor Ingresar Fechas de Cuota");return;}
	var URL = "../pl/fwsp.pl";
    var str = "lan="+lan+"&appid="+appid+"&clase="+clase+"&id="+id+"&cuotas="+cuo+"&periodos_vencidos="+periodos_v+"&mora_desde="+mora_desde+"&mora_hasta="+mora_hasta+"&inc_fie="+incFiestas+"&inc_int="+incInteres+"&inc_mul="+incMultas+"&inc_cor="+incCorriente+"&corriente_tasas="+corTasas+"&corriente_fiestas="+corFiestas+"&corriente_total="+corTotal+"&vencimientos="+expe;
    //alert(URL+"<>"+str);
    xmlHttp1	= GetXmlHttpObject(stateGetFinanciamiento);
    xmlHttp1.open("PUT",URL,true) ;
	xmlHttp1.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp1.send(str);
}
function stateGetFinanciamiento(){
    if (xmlHttp1.readyState==4 || xmlHttp1.readyState=="complete"){
        xmlHttpStream1=xmlHttp1.responseText;
		//alert(xmlHttpStream1)
		if(xmlHttpStream1!==""){CompletarPlan(xmlHttpStream1);}
    }
}
function CompletarPlan(PlanStream){
	var Cuotas_a = PlanStream.split("~~");
	//alert(Cuotas_a)
	var pro_cuo = 0;
	var incMultas	= document.form.multas.value;
	for(var a=0;a<Cuotas_a.length-1;a++ ){
		var CuotaMembers= Cuotas_a[a].split("|");
		var multaActual	= (CuotaMembers[7]*1);
		var valCuota	= CuotaMembers[12]*1;
		var valMoraTotal= CuotaMembers[8]*1;
		if (incMultas=="SI") {
			document.getElementById("chk_"+(a+1)).checked = true;			
			//alert(valMoraTotal+"<>"+multaActual);
			if (multaActual<multaMinima) {
				multaActual = multaMinima;
			}
			valMoraTotal = (CuotaMembers[4]*1)+(CuotaMembers[5]*1)+(CuotaMembers[6]*1)+multaActual;
			valCuota = valMoraTotal+(CuotaMembers[11]*1);
		}else{
			document.getElementById("chk_"+(a+1)).checked = false;
			document.getElementById("chk_"+(a+1)).disabled = true;
		}
		eval("document.form.pds_"+(a+1)+".value='"+CuotaMembers[1]+"'");
		eval("document.form.desde_"+(a+1)+".value='"+CuotaMembers[2]+"'");
		eval("document.form.hasta_"+(a+1)+".value='"+CuotaMembers[3]+"'");
		eval("document.form.mora_tasas_"+(a+1)+".value='"+CuotaMembers[4]+"'");
		eval("document.form.mora_fiestas_"+(a+1)+".value='"+CuotaMembers[5]+"'");
		eval("document.form.mora_intereses_"+(a+1)+".value='"+CuotaMembers[6]+"'");
		eval("document.form.mora_multas_"+(a+1)+".value='"+CuotaMembers[7]+"'");
		eval("document.form.mora_multa_minima_"+(a+1)+".value='"+multaActual.toFixed(2)+"'");
		eval("document.form.mora_total_"+(a+1)+".value='"+valMoraTotal.toFixed(2)+"'");
		eval("document.form.corriente_tasas_"+(a+1)+".value='"+CuotaMembers[9]+"'");
		eval("document.form.corriente_fiestas_"+(a+1)+".value='"+CuotaMembers[10]+"'");
		eval("document.form.corriente_total_"+(a+1)+".value='"+CuotaMembers[11]+"'");
		eval("document.form.total_"+(a+1)+".value='"+valCuota.toFixed(2)+"'");
		pro_cuo += valCuota;
	}
	document.form.d82_promedio.value = (Math.ceil((pro_cuo/(Cuotas_a.length-1)) * 100)/100).toFixed(2);
	if (document.form.d82_promedio.value>0) {document.getElementById("ajustador").disabled =false;}
	document.all.guardar_div.style.visibility='visible';
	document.all.generar_div.style.visibility='hidden';   
}
function saveFinanciamientoPlan(){
    var NewPlanStream = "";
    var T = document.getElementById('t1');
    for(var i=1;i<T.rows.length-1;i++){
		var x   = T.rows[i+1].cells[1].getElementsByTagName("input");
		var ymd = x[0].value.replace(/-/g,"");
        var v_ymd       = eval("document.form.v_"+ymd+".value");        
        var pds         = eval("document.form.pds_"+i+".value");
        var desde       = eval("document.form.desde_"+i+".value");
        var hasta       = eval("document.form.hasta_"+i+".value");
		var moraTasas	= eval("document.form.mora_tasas_"+i+".value");
		var moraFiestas	= eval("document.form.mora_fiestas_"+i+".value");
		var moraInteres = eval("document.form.mora_intereses_"+i+".value");
		var moraMultas	= eval("document.form.mora_multas_"+i+".value");
		var moraActual  = eval("document.form.mora_multa_minima_"+i+".value");
        var moraTotal   = eval("document.form.mora_total_"+i+".value");
        var corTasas	= eval("document.form.corriente_tasas_"+i+".value");
        var corFiestas	= eval("document.form.corriente_fiestas_"+i+".value");		
        var corTotal	= eval("document.form.corriente_total_"+i+".value");
        var total       = eval("document.form.total_"+i+".value");
        NewPlanStream += v_ymd+"|"+pds+"|"+desde+"|"+hasta+"|"+moraTasas+"|"+moraFiestas+"|"+moraInteres+"|"+moraMultas+"|"+moraActual+"|"+moraTotal+"|"+corTasas+"|"+corFiestas+"|"+corTotal+"|"+total+"~~";
    }
    document.form.plan.value  = NewPlanStream;
	//alert(document.form.plan.value);
    document.form.submit();
}
function CompletarFechas(FechasStream){
    var dtd      = "";
    var dth      = "";
    var pds      = "";
    var icc      = document.form.incluir_cc.value;
    var Fechas_a = FechasStream.split("~~");
    for(var a=0;a<Fechas_a.length-1;a++ ){
		var dtv  = Fechas_a[a].substr(0,4)+"-"+Fechas_a[a].substr(4,2)+"-"+Fechas_a[a].substr(6,2);
		var ymd  = Fechas_a[a];
		AddRow(dtv,ymd,pds,dtd,dth,'','','');
		Clean('dt_inicial_plan','dt_inicial_plan');
    }
	
}
function ShowCalendar(form,datetype,separator){
	if (!openwindow || openwindow.closed){
		console.log(form);
		console.log(datetype);
		console.log(separator);
		win ="window.open('/libraries/html/clnd.html?pbf="+form+"&datetype="+datetype+"&separator="+separator+"','Calendar','left=200,top=200,width=250,height=250,scrollbars=no,toolbar=no,menu=no')";
		openwindow=eval(win);
	}else{openwindow.focus()}
}
function AjustarCuotaFija(){
    var T1          = document.getElementById('t1');
	var cuo_val		= document.form.d82_cuota.value;    
    var cuo_pro 	= document.form.d82_promedio.value;
    var car_cor 	= document.form.cargo_corriente.value;
    var fie	   		= document.form.fiestas.value;
    var int	   		= document.form.intereses.value;
    var mul	   		= document.form.multas.value;
    var cc	   		= document.form.incluir_cc.value;
	
    document.form.d82_cuota.value = document.form.d82_promedio.value;
    document.form.tipo_cuota[1].selected=true;
    
    for (var i=1;i<T1.rows.length;i++){
        eval("document.form.pds_"+i+".value=''");
        eval("document.form.desde_"+i+".value=''");
        eval("document.form.hasta_"+i+".value=''");
		eval("document.form.mora_tasas_"+i+".value=''");
		eval("document.form.mora_fiestas_"+i+".value=''");
		eval("document.form.mora_intereses_"+i+".value=''");
		eval("document.form.mora_multas_"+i+".value=''");
		eval("document.form.mora_multa_minima_"+i+".value=''");
		eval("document.form.mora_total_"+i+".value=''");
		eval("document.form.corriente_tasas_"+i+".value=''");
		eval("document.form.corriente_fiestas_"+i+".value=''");
		eval("document.form.corriente_total_"+i+".value=''");
		if(cc=="SI"){
			eval("document.form.mora_total_"+i+".value="+(Math.round((cuo_pro-car_cor) * 100) / 100))
		}else{
			eval("document.form.mora_total_"+i+".value="+cuo_pro)
		}
        if(cc=="SI"){
			eval("document.form.corriente_total_"+i+".value="+car_cor)
		}else{
			eval("document.form.corriente_total_"+i+".value=0")
		}
        eval("document.form.total_"+i+".value="+cuo_pro);
    }    
}
function evalMulta(indx) {
	var moraTasas	= eval("document.form.mora_tasas_"+indx+".value");
	var moraFiestas	= eval("document.form.mora_fiestas_"+indx+".value");
	var moraInteres = eval("document.form.mora_intereses_"+indx+".value");
	var moraMultas	= eval("document.form.mora_multas_"+indx+".value");
	var multaActual = eval("document.form.mora_multa_minima_"+indx+".value");
	var moraTotal	= eval("document.form.mora_total_"+indx+".value");
	var corTotal	= eval("document.form.corriente_total_"+indx+".value");
	var valCuota	= eval("document.form.total_"+indx+".value"); 
	if(eval("document.form.chk_"+indx+".checked")){
		if (multaActual<multaMinima) {
			multaActual = multaMinima;
		}		
		valCuota = (moraTasas*1)+(moraFiestas*1)+(moraInteres*1)+(multaActual*1)+(corTotal*1);
	}else{
		valCuota= (moraTasas*1)+(moraFiestas*1)+(moraInteres*1)+(moraMultas*1)+(corTotal*1);
	}
	moraTotal= (valCuota*1)-(corTotal*1);
	eval("document.form.total_"+indx+".value='"+valCuota.toFixed(2)+"'");
	eval("document.form.mora_total_"+indx+".value='"+moraTotal.toFixed(2)+"'");
}