var xmlHttp;
var xmlHttpStream;
var xmlHttp1;
var xmlHttpStream1;
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;
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);
    Cell0.innerHTML = "<input type=text name=a"+count+" size=1 maxlength=2 class=my_style readonly value="+count+">";
    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+" size=4 maxlength=4 class=my_style value="+pds+">";
    Cell3.innerHTML = "<input type=text name=desde_"+count+" size=10 maxlength=10 class=my_style value="+dtd+">";
    Cell4.innerHTML = "<input type=text name=hasta_"+count+" size=10 maxlength=10 class=my_style value="+dth+">";
    Cell5.innerHTML = "<input type=text name=mora_"+count+" size=10 maxlength=10 class=my_style value="+mor+">";
    Cell6.innerHTML = "<input type=text name=corriente_"+count+" size=10 maxlength=10 class=my_style value="+cor+">";
    Cell7.innerHTML = "<input type=text name=total_"+count+" size=10 maxlength=10 class=my_style value="+tot+">";
    Cell8.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 GenerarFechasPlan(){
    var clase   	= "inmueble_balance";
    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<5){alert("Utilice Esta Opcion para Planes con Mas de 4 Cuotas");return}
	var URL	= "/cgi-bin/"+appid+"/pl/get_fechas_financiamiento.pl?lan="+lan+"&appid="+appid+"&id="+id+"&clase="+clase+"&dt_inicial="+inicial+"&cuotas="+cuo;
    xmlHttp	= GetXmlHttpObject(stateGetFechasFinanciamiento);
    xmlHttp.open("GET",URL,true) ;
    xmlHttp.send(null);
}
function stateGetFechasFinanciamiento(){
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
        xmlHttpStream=xmlHttp.responseText;
		//alert(xmlHttpStream);
		if(xmlHttpStream!=""){
			CompletarFechas(xmlHttpStream);
		}
    }
}
function GenerarPlan(){
    var mora_desde 	= document.form.dt_desde.value;
    var mora_hasta 	= document.form.dt_hasta.value;
    var periodos_v 	= document.form.periodos_vencidos.value;
    var cuo	   		= document.form.cuotas[document.form.cuotas.selectedIndex].value;
    var fie	   		= document.form.fiestas.value;
    var int	   		= document.form.intereses.value;
    var mul	   		= document.form.multas.value;
    var cobro_c	   	= document.form.incluir_cc.value;
    var cargo_c	   	= document.form.cargo_corriente.value;
    var T  	   		= document.getElementById('t1');
    var trows 	   	= T.rows;
    var expe	   	= "";
    for(var i=1;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	= "/cgi-bin/"+appid+"/pl/fwsp.pl?lan="+lan+"&appid="+appid+"&id="+id+"&clase="+clase+"_balance&mora_desde="+mora_desde+"&mora_hasta="+mora_hasta+"&periodos_vencidos="+periodos_v+"&cuotas="+cuo+"&fiestas="+fie+"&intereses="+int+"&multas="+mul+"&cobro_corriente="+cobro_c+"&cargo_corriente="+cargo_c+"&vencimientos="+expe;    
    //alert(URL);
    xmlHttp1	= GetXmlHttpObject(stateGetFinanciamiento);
    xmlHttp1.open("GET",URL,true) ;
    xmlHttp1.send(null);
}
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("~~");
	var pro_cuo = 0;
	for(var a=0;a<Cuotas_a.length-1;a++ ){
		var CuotaMembers  = Cuotas_a[a].split("|");
		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_"+(a+1)+".value="+CuotaMembers[4]);
		eval("document.form.corriente_"+(a+1)+".value="+CuotaMembers[5]);
		eval("document.form.total_"+(a+1)+".value="+CuotaMembers[6]);
		pro_cuo += (CuotaMembers[6]*1);
	}
	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 GuardarPlan(){
    var NewPlanStream = "";
    var T = document.getElementById('t1');
    for(var i=1;i<T.rows.length;i++){
		var x   = T.rows[i].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 mora        = eval("document.form.mora_"+i+".value");
        var corriente   = eval("document.form.corriente_"+i+".value");
        var total       = eval("document.form.total_"+i+".value");
        NewPlanStream += v_ymd+"|"+pds+"|"+desde+"|"+hasta+"|"+mora+"|"+corriente+"|"+total+"~~";
    }
    document.form.plan.value  = NewPlanStream;
    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){
		win ="window.open('/"+appid+"/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=''");
        if(cc=="SI"){eval("document.form.mora_"+i+".value="+(cuo_pro-car_cor))}else{eval("document.form.mora_"+i+".value="+cuo_pro)}
        if(cc=="SI"){eval("document.form.corriente_"+i+".value="+car_cor)}else{eval("document.form.corriente_"+i+".value=0")}
        eval("document.form.total_"+i+".value="+cuo_pro);
    }    
}