var FY_start_date = '01/04/2014';
var FY_end_date = '31/03/2015';
var AY_start_date = '01/04/2015';
var Filing_dueDate= '07/09/2015'; // Modified due to the due date extended for filing the return
var Int_start_date_234A = '08/09/2015'; // Modified due to the due date extended for filing the return

var slab1_end_date = '15/09/2014';
var slab2_start_date = '16/09/2014';
var slab2_end_date = '15/12/2014';
var slab3_start_date = '16/12/2014';
var slab3_end_date = '16/03/2015';
var slab4_start_date = '17/03/2015';
var Cg_ded_start_date = '31/03/2013';
var Cg_ded_end_date = '01/04/2018';

var globTempStcg1 = 0;
var globTempStcg2 = 0;
var globTempltcg1 = 0;
var globTempltcg2 = 0;

//To calculate all ITR2A calculations
function calcITR2(){
	try{
		var cgosIncome = {};
		initCgOsInc(cgosIncome);
		enableNRItables();
		calSchS('scheduleSalaryMain'); 
		scheduleHPCalcFor2();
		var simap = calculateOS(cgosIncome);
		calculateCYLA(cgosIncome);
		var amt5BBC = simap['5BBC'];
		var amt5Ea = simap['5Ea'];
		populateSI(cgosIncome,simap);
		calculatePartBTI_first();
		caclDedSchVIA();
		calcTotal80GDeductions('ded100PerWithoutQual',3,2,amt5BBC,amt5Ea);
		calcTotal80GDeductions('ded50WithoutQual',3,2,amt5BBC,amt5Ea);
		calcTotal80GDeductions('ded100Qual',3,2,amt5BBC,amt5Ea);
		calcTotal80GDeductions('ded50WithQual',3,2,amt5BBC,amt5Ea);
		caclDedSchVIA();
		calculateNetAgricultureIncomeforEI();
		calTotalEI();
		totAmtOfSched5A();
		calculatePartBTI_second();
		calculateTiTti(cgosIncome);
		calculatePartBTTI_second(cgosIncome);
		panValidation80G('ded100PerWithoutQual');
		panValidation80G('ded50WithoutQual');
		panValidation80G('ded100Qual');
		panValidation80G('ded50WithQual');
		calculateTDS();
		calculateTotalTaxIT('scheduleIt');

	}catch(e){
		alert('Exception in calcITR2 method:'+e);
	}
}

//To enable NRI tables based on the status
function enableNRItables(){
	 enableTableForNRI('partAGEN1.filingStatus.residentialStatus','NRI','scheduleOsNriIncTaxDtaa');
}

//To initiate CG and OS income values
function initCgOsInc(cgosIncome){
	cgosIncome.osInc = {};
	cgosIncome.osInc.sec115A_1_a_i = 0;
	cgosIncome.osInc.sec115A_1_a_ii = 0;
	cgosIncome.osInc.sec115A_1_a_iia = 0;
	cgosIncome.osInc.sec115A_1_a_iiaa = 0;
	cgosIncome.osInc.sec115A_1_a_iiab = 0;
	cgosIncome.osInc.sec115A_1_a_iii = 0;
	cgosIncome.osInc.sec115A_1_b_A = 0;
	cgosIncome.osInc.sec115A_1_b_B = 0;
	cgosIncome.osInc.sec115AC_1_a_b = 0;
	cgosIncome.osInc.sec115ACA_1_a = 0;
	cgosIncome.osInc.sec115AD_1_i = 0;
	cgosIncome.osInc.sec115BBA = 0;
	cgosIncome.osInc.sec115BBC = 0;
	cgosIncome.osInc.sec115BBE = 0;
    cgosIncome.osInc.sec115BB = 0;
	cgosIncome.osInc.sec115E_a = 0;
	cgosIncome.osInc.sec111 = 0;
}

//To validate schedule FSI
function validateFSI(){
	var table=document.getElementById('scheduleFSI');
    var noOfRows=table.rows.length;
    var indexValue=eval(((parseInt(noOfRows,10)-4)/6));
    var empty1,empty2,empty3,empty4;
    for(var i=0;i<indexValue;i++){	
		if(document.getElementsByName('itrScheduleFSI.scheduleFSI['+i+'].countryCode')[0].value!=''){
		var empty = true;
			var errors = ['Income from outside India(included in PART B-TI) is required',
			              'Tax paid outside India is required',
						  'Tax payable on such income under normal provisions in India is required',
			              'Relevant article of DTAA if relief claimed u/s 90 or 90A is required'];
			empty1 = empty && !validateAllFilled(['itrScheduleFSI.scheduleFSI['+i+'].incFromSal.incFrmOutsideInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incFromSal.taxPaidOutsideInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incFromSal.taxPayableinInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incFromSal.dtaaReliefUs90or90A'],errors);
			empty2 = empty && !validateAllFilled(['itrScheduleFSI.scheduleFSI['+i+'].incFromHP.incFrmOutsideInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incFromHP.taxPaidOutsideInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incFromHP.taxPayableinInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incFromHP.dtaaReliefUs90or90A'],errors);
			empty3 = empty && !validateAllFilled(['itrScheduleFSI.scheduleFSI['+i+'].incCapGain.incFrmOutsideInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incCapGain.taxPaidOutsideInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incCapGain.taxPayableinInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incCapGain.dtaaReliefUs90or90A'],errors);
			empty4 = empty && !validateAllFilled(['itrScheduleFSI.scheduleFSI['+i+'].incOthSrc.incFrmOutsideInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incOthSrc.taxPaidOutsideInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incOthSrc.taxPayableinInd',
			                                     'itrScheduleFSI.scheduleFSI['+i+'].incOthSrc.dtaaReliefUs90or90A'],errors);
			if(empty1&&empty2&&empty3&&empty4){
	            j.setFieldError('itrScheduleFSI.scheduleFSI['+i+'].countryCode','Please fill atleast one income');
	            addErrorXHTML(document.getElementsByName('itrScheduleFSI.scheduleFSI['+i+'].countryCode')[0],'Please fill atleast one income',true);
			}
		}
    }
}

//To validate All Filled values in schedule FSI
function validateAllFilled(fieldNames,errors){
	var fields = [];
	var filled = 0;
	for(var i=0; i<fieldNames.length; i++){
		fields[i] = document.getElementsByName(fieldNames[i])[0];
		if(fields[i].value!='' && fields[i].value!=undefined){
			filled++;
		}
	}
	if(filled>0){
		for(var i=0; i<fieldNames.length; i++){
			if(fields[i].value=='' || fields[i].value==undefined){
				if(i==fieldNames.length-1){
					if(Math.min(coalesce(fields[1].value),coalesce(fields[2].value)) == parseInt(0)){
						continue;
					}
				}
	            j.setFieldError(fieldNames[i],errors[i]);
	            addErrorXHTML(fields[i],errors[i],true);
	            break;
			}
		}		
		return true;
	}
	return false;
}

//To validate schedule CG Deduction Dates
function validateCGDedDate(){
	var tab = document.getElementById('schduleCGDed');
	var selects  = tab.getElementsByTagName('SELECT');
	
	for(var i=0; i<selects.length;i++){
		var name = selects[i].name;
		var index = name.substring(name.indexOf("[")+1,name.indexOf("]"));
		var dedDt = document.getElementsByName('scheduleCGPost45.deducClaimInfo.deducClaimDtls['+index+'].dateofAcquist')[0];
		if(dedDt!='' && selects[i].value!=''){
			if(isFirstDateBefore(dedDt.value, Cg_ded_start_date) || isFirstDateBefore(Cg_ded_end_date, dedDt.value)){
		            j.setFieldError(dedDt.name,'Date must be between 01/04/2013 and 31/03/2018');
		            addErrorXHTML(dedDt,'Date must be between 01/04/2013 and 31/03/2018',true);
			}	
		}
	}
}

//To do caluclations or validations on click on Submit button
function validateOnSubmit() {
	try{
		checkDropdownSelectedin1d();
		validatePanStatus();
		validateScheduleHP();
		calculateTDS();
		validateHPRent();
		checkUniqueOSSec();
		checkEmptyAmtSpouse();
		CheckHPShareProperty();
		checkSchedule5A();
		onStatusChange();
		calSchS('scheduleSalaryMain'); 
		checkNoOfRowsFilled();
		panValidation80G('ded100PerWithoutQual');
		panValidation80G('ded50WithoutQual');
		panValidation80G('ded100Qual');
		panValidation80G('ded50WithQual');
		calculateTDS();
		calculateTotalTaxIT('scheduleIt');
		validatePassport();
	    //Always keep alertItr2User() at the last
		alertItr2User();

	}catch(e){
		alert('Exception in validateOnSubmit method ' + e);
	}
}

//To caluclate interest calculations On clicking on Re calculate button
function calculateTax(){
	clearOldValues();
	calcITR2();
}

//To calculate schedule VIA
function caclDedSchVIA(){
	try{
	
		var grossTotInc = document.getElementsByName('partBTI.grossTotalIncome')[0]; 
		var incChrgable=document.getElementsByName('partBTI.incChargeTaxSplRate111A112')[0]; 
		var resStatus=document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value;
		var status=document.getElementsByName('partAGEN1.personalInfo.status')[0].value;

		if(parseInt(grossTotInc.value ,10) <0){
			
			grossTotInc.value='0';
		}

		if(parseInt(incChrgable.value ,10) <0){
			
			incChrgable.value='0';
		}
	var gtiLimit=eval(parseInt(coalesce(grossTotInc.value),10)-parseInt(coalesce(incChrgable.value),10));
	
	if(gtiLimit<0){
		gtiLimit=0;
	}
	
	var sec80C=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80C')[0];
	var sec80CSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80C')[0];
	
	var sec80CCC=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80CCC')[0];
	var sec80CCCSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80CCC')[0];
	
	var sec80CCDi=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80CCDi')[0];
	var sec80CCDiSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80CCDi')[0];
	
	var sec80CCDii=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80CCDii')[0];
	var sec80CCDiiSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80CCDii')[0];
	
	var sec80CCG=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80CCG')[0];
	var sec80CCGSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80CCG')[0];
	
	var sec80D=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80D')[0];
	var sec80DSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80D')[0];
	
	var sec80DD=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80DD')[0];
	var sec80DDSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80DD')[0];
	
	var sec80DDB=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80DDB')[0];
	var sec80DDBSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80DDB')[0];
	
	var sec80EE=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80EE')[0];
	var sec80EESysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80EE')[0];
	
	var sec80E=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80E')[0];
	var sec80ESysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80E')[0];
	
	var sec80G=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80G')[0]; 
	var sec80GSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80G')[0]; 
	var totalElgblAmt80G=document.getElementsByName('schedule80G.totalEligibleDonationsUs80G')[0];

	var sec80GG=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80GG')[0]; 
	var sec80GGSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80GG')[0]; 

	var sec80GGC=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80GGC')[0]; 
	var sec80GGCSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80GGC')[0]; 

	var sec80GGA=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80GGA')[0]; 
	var sec80GGASysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80GGA')[0]; 


	var sec80QQB=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80QQB')[0]; 
	var sec80QQBSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80QQB')[0]; 
	
	var sec80RRB=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80RRB')[0]; 
	var sec80RRBSysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80RRB')[0]; 
	
	var sec80TTA=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80TTA')[0]; 
	var sec80TTASysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80TTA')[0]; 
	
	var sec80U=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80U')[0]; 
	var sec80USysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80U')[0]; 


	var totalDedVIA=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.totalChapVIADeductions')[0]; totalDedVIA.value=coalesce(totalDedVIA.value);
	var totalDedVIASysCal=document.getElementsByName('scheduleVIA.deductUndChapVIA.totalChapVIADeductions')[0]; totalDedVIASysCal.value=coalesce(totalDedVIASysCal.value);

	var salaries=document.getElementsByName('partBTI.salaries')[0];

	//80C
	
	if(parseInt(coalesce(gtiLimit),10)> eval('100000') ){
		if( parseInt(coalesce(sec80C.value),10) > eval('150000')) {
			sec80CSysCal.value = '150000' ;
		} else {
			sec80CSysCal.value = parseInt(coalesce(sec80C.value),10);
		}

	}else{
		
		if( parseInt(coalesce(sec80C.value),10) > parseInt(coalesce(gtiLimit),10)) {
			sec80CSysCal.value = gtiLimit ;
		} else {
			sec80CSysCal.value = parseInt(coalesce(sec80C.value),10);
		}
	}
	//80CCC

		if(status =='I'){
			
	if(parseInt(coalesce(gtiLimit),10)> eval('100000') ){		
		if( parseInt(coalesce(sec80CCC.value),10) > eval('100000')) {
			sec80CCCSysCal.value = '100000' ;
		} else {
			sec80CCCSysCal.value= parseInt(coalesce(sec80CCC.value),10);
		}
		
	 }else{
		 
		 if( parseInt(coalesce(sec80CCC.value),10) > parseInt(coalesce(gtiLimit),10)) {
				sec80CCCSysCal.value = gtiLimit ;
			} else {
				sec80CCCSysCal.value= parseInt(coalesce(sec80CCC.value),10);
			}
				
			}
		
	}else{
		
		sec80CCCSysCal.value= parseInt('0',10);
		
	}

	
	
	// CHECK FOR 80CCDii (EMPLOYER CONTRIBUTIION)
	var temp = Math.round(eval(parseInt(coalesce(salaries.value),10)) * eval('0.10'));
	if(status =='I' ){
	if( parseInt(sec80CCDii.value,10) > temp ) {
		sec80CCDiiSysCal.value = temp ;
	} else {
		sec80CCDiiSysCal.value = parseInt(sec80CCDii.value,10);
	}
	}
	else{
		sec80CCDiiSysCal.value=parseInt('0',10);
	}

	// CHECK FOR 80CCDi(EMPLOYEE)

	var salUppLimit = Math.round(eval(parseInt(coalesce(salaries.value),10)) * eval('0.10'));
	var gtiUppLimit = Math.round(eval(parseInt(coalesce(grossTotInc.value),10)) * eval('0.10'));
	
	
	if(status =='I'){		
	if(parseInt(coalesce(salaries.value)) == parseInt('0' , 10)){
			if(gtiUppLimit > parseInt('100000' ,10)){
				if( parseInt(coalesce(sec80CCDi.value),10) > eval('100000')) {
					sec80CCDiSysCal.value = '100000' ;
				} else {
					sec80CCDiSysCal.value = parseInt(coalesce(sec80CCDi.value),10);
				}
			} else {
				if( parseInt(coalesce(sec80CCDi.value),10) > gtiUppLimit ) {
					sec80CCDiSysCal.value = gtiUppLimit ;
				} else {
					sec80CCDiSysCal.value = parseInt(coalesce(sec80CCDi.value),10);
				}
				}	
	}else{
	
		if(salUppLimit > parseInt('100000' ,10)){
			if( parseInt(coalesce(sec80CCDi.value),10) > eval('100000')) {
				sec80CCDiSysCal.value = '100000' ;
			} else {
				sec80CCDiSysCal.value = parseInt(coalesce(sec80CCDi.value),10);
			}
		} else {
			if( parseInt(coalesce(sec80CCDi.value),10) > salUppLimit ) {
				sec80CCDiSysCal.value = salUppLimit ;
			} else {
				sec80CCDiSysCal.value = parseInt(coalesce(sec80CCDi.value),10);
			}
		}	
		
	}
	} else if(status =='H' ){
		sec80CCDiSysCal.value = parseInt('0',10);
	}
		//80CCG
	if(status =='I'){	
	 if(resStatus=='RES' || resStatus=='NOR'){
		 
		 if (parseInt(coalesce(grossTotInc.value), 10) <= parseInt('1200000', 10)) {
			 
			 if(gtiLimit > parseInt('25000' ,10)){
				 
				 if( parseInt(coalesce(sec80CCG.value),10) > eval('25000')){
					 sec80CCGSysCal.value = '25000';
				  } else {
					  sec80CCGSysCal.value=  parseInt(coalesce(sec80CCG.value),10);
				  } 
				 
				 
			 }else{
				 
				 
				 if( parseInt(coalesce(sec80CCG.value),10) > gtiLimit ) {
					 sec80CCGSysCal.value = gtiLimit ;
					} else {
						sec80CCGSysCal.value = parseInt(coalesce(sec80CCG.value),10);
					}
					}
				 
			 }else{
				 sec80CCGSysCal.value= parseInt('0',10);
			 }
			 
			 
		 }else{
			 
			 sec80CCGSysCal.value= parseInt('0',10);
		 }
		 
		 
	 }else{
		sec80CCGSysCal.value= parseInt('0',10);
	}
		
	 //80D
		 
	 var age = calcAge();
	if(status =='I'){
		var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value; 
		if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && (resStatus== 'RES' || resStatus== 'NOR') && age > eval('59')){
			
			if(gtiLimit > parseInt('40000' ,10)){
			  if( parseInt(coalesce(sec80D.value),10) > eval('40000')){
				 sec80DSysCal.value = '40000';
			  } else {
				 sec80DSysCal.value=  parseInt(coalesce(sec80D.value),10);
			  }
			
			} else {
					if( parseInt(coalesce(sec80D.value),10) > gtiLimit ) {
						sec80DSysCal.value = gtiLimit ;
					} else {
						sec80DSysCal.value = parseInt(coalesce(sec80D.value),10);
					}
					}
			
			
		}else {
			
			if(gtiLimit > parseInt('35000' ,10)){
			if( parseInt(coalesce(sec80D.value),10) > eval('35000')){
				
				sec80DSysCal.value = '35000';
			} else {
				sec80DSysCal.value = parseInt(coalesce(sec80D.value),10);
			}
			}else{
				
				if( parseInt(coalesce(sec80D.value),10) > gtiLimit ) {
					sec80DSysCal.value = gtiLimit ;
				} else {
					sec80DSysCal.value = parseInt(coalesce(sec80D.value),10);
				}
				
			}
			
		}
		} else {
			if(gtiLimit > parseInt('20000' ,10)){
		if( parseInt(coalesce(sec80D.value),10) > eval('20000')){
				
				sec80DSysCal.value = '20000';
			} else {
				sec80DSysCal.value = parseInt(coalesce(sec80D.value),10);
			}
			}else{
				
				if( parseInt(coalesce(sec80D.value),10) > gtiLimit ) {
					sec80DSysCal.value = gtiLimit ;
				} else {
					sec80DSysCal.value = parseInt(coalesce(sec80D.value),10);
				}
			}
			}
		
// CHECK FOR 80DD	
	if(resStatus =='RES' || resStatus =='NOR'){
		
		if(parseInt(coalesce(gtiLimit),10)> eval('100000') ){
		
			if( parseInt(coalesce(sec80DD.value),10) > eval('100000')){
				sec80DDSysCal.value= '100000';
			}else{
				sec80DDSysCal.value = parseInt(coalesce(sec80DD.value),10);
			}
			
		}else{
			
			if( parseInt(coalesce(sec80DD.value),10) > eval(parseInt(coalesce(gtiLimit),10))){
				sec80DDSysCal.value= gtiLimit;
			}else{
				sec80DDSysCal.value = parseInt(coalesce(sec80DD.value),10);
			}
			
		}
		}else {
			sec80DDSysCal.value= parseInt('0',10);
		}
//CHECK FOR 80DDB
	if(resStatus =='RES' || resStatus =='NOR'){
		
		if(parseInt(coalesce(gtiLimit),10)> eval('60000') ){
		
		if(parseInt(coalesce(sec80DDB.value) ,10) > eval('60000')){
				sec80DDBSysCal.value = '60000';
			} else {
				sec80DDBSysCal.value = parseInt(coalesce(sec80DDB.value) ,10);
			}
		
		}else{
			if(parseInt(coalesce(sec80DDB.value) ,10) > eval(parseInt(coalesce(gtiLimit),10))){
				sec80DDBSysCal.value = gtiLimit;
			} else {
				sec80DDBSysCal.value = parseInt(coalesce(sec80DDB.value) ,10);
			}
		}
	} else {
		sec80DDBSysCal.value =parseInt('0',10);
	}
	

	// CHECK FOR 80E
	if(status =='I'){
		if(eval(parseInt(coalesce(gtiLimit),10)>parseInt(coalesce(sec80E.value),10))){
			sec80ESysCal.value = parseInt(coalesce(sec80E.value),10);
		}else{
			sec80ESysCal.value = parseInt(coalesce(gtiLimit),10);
		}
	}else{
		sec80ESysCal.value = parseInt('0',10);
	}
	
	
	// CHECK FOR 80EE
	if(status =='I'){
            
            if(parseInt(coalesce(gtiLimit),10)> eval('100000') ){
		
		if(parseInt(coalesce(sec80EE.value) ,10) > eval('100000')){
				sec80EESysCal.value = '100000';
			} else {
				sec80EESysCal.value = parseInt(coalesce(sec80EE.value) ,10);
			}
		
		}else{
			if(parseInt(coalesce(sec80EE.value) ,10) > eval(parseInt(coalesce(gtiLimit),10))){
				sec80EESysCal.value = gtiLimit;
			} else {
				sec80EESysCal.value = parseInt(coalesce(sec80EE.value) ,10);
			}
		}
            
	}else{
		sec80EESysCal.value = parseInt('0',10);
	}
		 
	//Autopopulate 80G
	sec80GSysCal.value=totalElgblAmt80G.value;
	sec80G.value=totalElgblAmt80G.value;
	
	//80GGA
	if(eval(parseInt(coalesce(sec80GGA.value),10)>parseInt(coalesce(gtiLimit),10))){

		sec80GGASysCal.value=parseInt(coalesce(gtiLimit),10);
	}else{
		sec80GGASysCal.value = parseInt(coalesce(sec80GGA.value),10);
	}
	
	//80GGC
	if(eval(parseInt(coalesce(sec80GGC.value),10)>parseInt(coalesce(gtiLimit),10))){

		sec80GGCSysCal.value=parseInt(coalesce(gtiLimit),10);
	}else{
		sec80GGCSysCal.value = parseInt(coalesce(sec80GGC.value),10);
	}

	
//80QQB
	
	
	if(status =='I'){
	
	if(resStatus=='RES' || resStatus=='NOR'){	
		if(parseInt(coalesce(gtiLimit),10)> eval('300000') ){
			if( parseInt(coalesce(sec80QQB.value),10) > eval('300000')) {
				sec80QQBSysCal.value = '300000' ;
			} else {
				sec80QQBSysCal.value = parseInt(coalesce(sec80QQB.value),10);
			}

		}else{
			
			if( parseInt(coalesce(sec80QQB.value),10) > parseInt(coalesce(gtiLimit),10)) {
				sec80QQBSysCal.value = gtiLimit ;
			} else {
				sec80QQBSysCal.value = parseInt(coalesce(sec80QQB.value),10);
			}
		}	
	}else{
		
		sec80QQBSysCal.value =parseInt('0',10);
	}
	}else{
		sec80QQBSysCal.value =parseInt('0',10);
	}
	

	
	
	
	// CHECK FOR 80RRB
	
	if(status =='I'){
		
	
		if(resStatus=='RES' || resStatus=='NOR'){	
			if(parseInt(coalesce(gtiLimit),10)> eval('300000') ){
				if( parseInt(coalesce(sec80RRB.value),10) > eval('300000')) {
					sec80RRBSysCal.value = '300000' ;
				} else {
					sec80RRBSysCal.value = parseInt(coalesce(sec80RRB.value),10);
				}

			}else{
				
				if( parseInt(coalesce(sec80RRB.value),10) > parseInt(coalesce(gtiLimit),10)) {
					sec80RRBSysCal.value = gtiLimit ;
				} else {
					sec80RRBSysCal.value = parseInt(coalesce(sec80RRB.value),10);
				}
			}	
		}else{
			
			sec80RRBSysCal.value =parseInt('0',10);
		}
		
	}else{
		sec80RRBSysCal.value =parseInt('0',10);
	}

	
	// CHECK FOR 80TTA
	
	var incOs = document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.interestGross')[0].value;
	if( parseInt(coalesce(gtiLimit),10) >0 ){
		if(parseInt(isNVL(sec80TTA.value),10) > parseInt('0',10)){
			sec80TTASysCal.value=Math.min(parseInt(incOs,10),parseInt(gtiLimit ,10),10000,parseInt(isNVL(sec80TTA.value),10));
		} else{
			sec80TTASysCal.value= parseInt('0',10);
		}
	} else {
		sec80TTASysCal.value= parseInt('0',10);
	}
	
	
	
	
	// CHECK FOR 80U
	
	if(status =='I'){
		if(resStatus=='RES' || resStatus=='NOR'){	
			if(parseInt(coalesce(gtiLimit),10)> eval('100000') ){
				if( parseInt(coalesce(sec80U.value),10) > eval('100000')) {
					sec80USysCal.value = '100000' ;
				} else {
					sec80USysCal.value = parseInt(coalesce(sec80U.value),10);
				}

			}else{
				
				if( parseInt(coalesce(sec80U.value),10) > parseInt(coalesce(gtiLimit),10)) {
					sec80USysCal.value = gtiLimit ;
				} else {
					sec80USysCal.value = parseInt(coalesce(sec80U.value),10);
				}
			}	
		}else{
			
			sec80USysCal.value =parseInt('0',10);
		}
				
	}else{
		sec80USysCal.value =parseInt('0',10);
	}
	
	

	checkSum80C80CCC();

	sumUserEntrdDed();
	sec80GGSysCal.value=0;
	sumDeductionsWithout80GG(sec80CSysCal,sec80CCCSysCal,sec80CCDiSysCal,sec80CCDiiSysCal,
			sec80DSysCal,sec80DDSysCal,sec80DDBSysCal,sec80ESysCal,sec80EESysCal,sec80GSysCal,sec80GGCSysCal,
			sec80USysCal,sec80CCGSysCal,sec80RRBSysCal,sec80QQBSysCal,sec80TTASysCal,sec80GGASysCal);

	// CHECK FOR 80GG again
	var totInc = document.getElementsByName('partBTI.totalIncome')[0];	
	if(totInc.value < 0){	
		totInc.value = eval(parseInt('0', 10));
	}
	var oneFrthTI =  Math.round(eval(totInc.value) * eval(0.25));
	
	if(status =='I' ){		
		if(eval(oneFrthTI) < eval('24000')) {
			if(eval(sec80GG.value) > eval(oneFrthTI)){
				sec80GGSysCal.value = eval(oneFrthTI);
			} else {
				sec80GGSysCal.value = sec80GG.value;
			}
		} else{
			if(eval(sec80GG.value) > eval('24000')){
				sec80GGSysCal.value = eval('24000');
			}else {
				sec80GGSysCal.value = sec80GG.value;
			}
		}
	}else{		
		sec80GGSysCal.value = eval(parseInt('0', 10));
	}
	
	
	// Do the sum of deductions again after adding 80GG and 80G
	sumDeductions(sec80CSysCal,sec80CCCSysCal,sec80CCDiSysCal,sec80CCDiiSysCal,
			sec80DSysCal,sec80DDSysCal,sec80DDBSysCal,sec80ESysCal,sec80EESysCal,sec80GSysCal,sec80GGSysCal,sec80GGCSysCal,
			sec80USysCal,sec80CCGSysCal,sec80RRBSysCal,sec80QQBSysCal,sec80TTASysCal,sec80GGASysCal);
	



	}catch(e){
		alert('Exception in Schedule V1A method ' +e);
	}

}

//To calculate sum of Deductions entered by user
function sumUserEntrdDed() {

var sec80C=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80C')[0];
var sec80CCC=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80CCC')[0];	
var sec80CCDi=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80CCDi')[0];
var sec80CCDii=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80CCDii')[0];
var sec80CCG=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80CCG')[0];
var sec80D=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80D')[0];
var sec80DD=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80DD')[0];
var sec80DDB=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80DDB')[0];
var sec80E=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80E')[0];
var sec80EE=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80EE')[0];
var sec80G=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80G')[0];
var sec80GG=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80GG')[0]; 
var sec80GGC=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80GGC')[0]; 	
var sec80GGA=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80GGA')[0]; 
var sec80QQB=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80QQB')[0]; 
var sec80RRB=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80RRB')[0]; 
var sec80TTA=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80TTA')[0]; 
var sec80U=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80U')[0];

	var userEntrdDed = document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.totalChapVIADeductions')[0];
	userEntrdDed.value = eval(parseInt(coalesce(sec80C.value) ,10))+
						 eval(parseInt(coalesce(sec80CCC.value) ,10))+
						 eval(parseInt(coalesce(sec80CCDi.value) ,10))+
						 eval(parseInt(coalesce(sec80CCDii.value) ,10))+
						 eval(parseInt(coalesce(sec80D.value) ,10))+
						 eval(parseInt(coalesce(sec80DD.value) ,10))+
						 eval(parseInt(coalesce(sec80DDB.value) ,10))+
						 eval(parseInt(coalesce(sec80E.value) ,10))+
						 eval(parseInt(coalesce(sec80EE.value) ,10))+
						 eval(parseInt(coalesce(sec80G.value) ,10))+
						 eval(parseInt(coalesce(sec80GG.value) ,10))+
						 eval(parseInt(coalesce(sec80GGC.value) ,10))+
						 eval(parseInt(coalesce(sec80U.value) ,10))+
						 eval(parseInt(coalesce(sec80CCG.value) ,10))+
						 eval(parseInt(coalesce(sec80RRB.value) ,10))+
						 eval(parseInt(coalesce(sec80QQB.value) ,10))+
						 eval(parseInt(coalesce(sec80TTA.value) ,10))+
						 eval(parseInt(coalesce(sec80GGA.value) ,10));
						
	}

//To calculate sum of 80G sections
function checkSum80C80CCC(){
	var sec80CSysCalc = document.getElementsByName('scheduleVIA.deductUndChapVIA.section80C')[0];
	var sec80CCCSysCalc = document.getElementsByName('scheduleVIA.deductUndChapVIA.section80CCC')[0];
	var sec80CCDempeContrSysCalc = document.getElementsByName('scheduleVIA.deductUndChapVIA.section80CCDi')[0];
	var netSum = eval(sec80CSysCalc.value) + eval(sec80CCCSysCalc.value) + eval(sec80CCDempeContrSysCalc.value);
	var maxAmount = getMaxLimitAmount();
	
	if(eval(netSum) >  eval(maxAmount)) {
		var residue = eval(netSum) - eval(maxAmount);
		if(sec80CCDempeContrSysCalc.value >= residue) {
			sec80CCDempeContrSysCalc.value = eval(sec80CCDempeContrSysCalc.value) - eval(residue);
		}else {
			residue = eval(residue) - eval(sec80CCDempeContrSysCalc.value);
			sec80CCDempeContrSysCalc.value =eval('0');

			if(sec80CCCSysCalc.value >= residue){
				sec80CCCSysCalc.value = eval(sec80CCCSysCalc.value) -eval(residue);
			} else {
				residue = eval(residue) - eval(sec80CCCSysCalc.value);
				sec80CCCSysCalc.value =eval('0');
			}
		}
	}
}

//to get Max Limit Amount
function getMaxLimitAmount() {
	var gtaAmount = document.getElementsByName('partBTI.grossTotalIncome')[0].value;
	var maxAmount = eval('150000');
	if(gtaAmount >= eval('150000')) {
		return maxAmount;
	} else {
		return gtaAmount;
	}
	
}

//To calculate sum of dedections
function sumDeductions(sec80CSysCalc,sec80CCCSysCalc,sec80CCDiSysCalc,sec80CCDiiSysCalc,
	sec80DSysCalc,sec80DDSysCalc,sec80DDBSysCalc,sec80ESysCalc,sec80EESysCalc,sec80GSysCalc,sec80GGSysCalc,sec80GGCSysCalc,
	sec80USysCalc,sec80CCGSysCalc,sec80RRBSysCalc,sec80QQBSysCalc,sec80TTASysCalc,sec80GGASysCal){

sec80CSysCalc.value 			= coalesce(sec80CSysCalc.value); 				sec80CCCSysCalc.value			= coalesce(sec80CCCSysCalc.value);
sec80CCDiSysCalc.value 		= coalesce(sec80CCDiSysCalc.value); 				sec80CCDiiSysCalc.value 	= coalesce(sec80CCDiiSysCalc.value);
sec80DSysCalc.value 			= coalesce(sec80DSysCalc.value);
sec80DDSysCalc.value 			= coalesce(sec80DDSysCalc.value); 				sec80DDBSysCalc.value			= coalesce(sec80DDBSysCalc.value);
sec80ESysCalc.value 			= coalesce(sec80ESysCalc.value); 				sec80EESysCalc.value 			= coalesce(sec80EESysCalc.value);
sec80GSysCalc.value 			= coalesce(sec80GSysCalc.value);
sec80GGSysCalc.value 			= coalesce(sec80GGSysCalc.value); 				sec80GGASysCal.value=coalesce(sec80GGASysCal.value);
sec80GGCSysCalc.value 			= coalesce(sec80GGCSysCalc.value); 				sec80USysCalc.value 			= coalesce(sec80USysCalc.value);
sec80CCGSysCalc.value 			= coalesce(sec80CCGSysCalc.value);				sec80RRBSysCalc.value 			= coalesce(sec80RRBSysCalc.value);
sec80QQBSysCalc.value 			= coalesce(sec80QQBSysCalc.value);				sec80TTASysCalc.value 			= coalesce(sec80TTASysCalc.value);


var dedVIA = document.getElementsByName('scheduleVIA.deductUndChapVIA.totalChapVIADeductions')[0];
var temp2 = eval(sec80CSysCalc.value) + eval(sec80CCCSysCalc.value) + eval(sec80CCDiSysCalc.value) +
			eval(sec80CCDiiSysCalc.value) + eval(sec80DSysCalc.value) +
			eval(sec80DDSysCalc.value) + eval(sec80DDBSysCalc.value) + eval(sec80ESysCalc.value) + eval(sec80EESysCalc.value) +
			eval(sec80GSysCalc.value) + eval(sec80GGSysCalc.value) + eval(sec80GGASysCal.value)+
			eval(sec80GGCSysCalc.value)+ eval(sec80USysCalc.value)+ eval(sec80CCGSysCalc.value)+ eval(sec80RRBSysCalc.value)+ 
			eval(sec80QQBSysCalc.value)+ eval(sec80TTASysCalc.value);
			

var grossTotInc = document.getElementsByName('partBTI.grossTotalIncome')[0]; 
var incChrgable=document.getElementsByName('partBTI.incChargeTaxSplRate111A112')[0];
var gtiLimit=eval(parseInt(coalesce(grossTotInc.value),10)-parseInt(coalesce(incChrgable.value),10));

if(gtiLimit<0){
	gtiLimit=0;
}

if(coalesce(grossTotInc.value) > parseInt('0',10)){
	if( temp2 >  parseInt(coalesce(gtiLimit) ,10)){
		dedVIA.value = parseInt(coalesce(gtiLimit) ,10);
	} else{
		dedVIA.value = temp2;
	}
}else{
	dedVIA.value = temp2;
}

}

//To calculate sum of Deductions Without 80GG
function sumDeductionsWithout80GG(sec80CSysCalc,sec80CCCSysCalc,sec80CCDiSysCalc,sec80CCDiiSysCalc,
	sec80DSysCalc,sec80DDSysCalc,sec80DDBSysCalc,sec80ESysCalc,sec80EESysCalc,sec80GSysCalc,sec80GGCSysCalc,
	sec80USysCalc,sec80CCGSysCalc,sec80RRBSysCalc,sec80QQBSysCalc,sec80TTASysCalc,sec80GGASysCal){

sec80CSysCalc.value = coalesce(sec80CSysCalc.value); 				sec80CCCSysCalc.value	= coalesce(sec80CCCSysCalc.value);
sec80CCDiSysCalc.value 	= coalesce(sec80CCDiSysCalc.value); 		sec80CCDiiSysCalc.value = coalesce(sec80CCDiiSysCalc.value);
sec80DSysCalc.value = coalesce(sec80DSysCalc.value);				sec80GGASysCal.value=coalesce(sec80GGASysCal.value);
sec80DDSysCalc.value = coalesce(sec80DDSysCalc.value); 				sec80DDBSysCalc.value	= coalesce(sec80DDBSysCalc.value);
sec80ESysCalc.value = coalesce(sec80ESysCalc.value); 				
sec80EESysCalc.value = coalesce(sec80EESysCalc.value); sec80GSysCalc.value 	= coalesce(sec80GSysCalc.value);
sec80GGCSysCalc.value = coalesce(sec80GGCSysCalc.value); 			sec80USysCalc.value 	= coalesce(sec80USysCalc.value);
sec80CCGSysCalc.value = coalesce(sec80CCGSysCalc.value);			sec80RRBSysCalc.value 	= coalesce(sec80RRBSysCalc.value);
sec80QQBSysCalc.value = coalesce(sec80QQBSysCalc.value);			sec80TTASysCalc.value 	= coalesce(sec80TTASysCalc.value);


var dedVIA = document.getElementsByName('scheduleVIA.deductUndChapVIA.totalChapVIADeductions')[0];
var temp2 = eval(sec80CSysCalc.value) + eval(sec80CCCSysCalc.value) + eval(sec80CCDiiSysCalc.value) +
			eval(sec80CCDiSysCalc.value) + eval(sec80DSysCalc.value) +eval(sec80GGASysCal.value)+
		eval(sec80DDSysCalc.value) + eval(sec80DDBSysCalc.value) + eval(sec80ESysCalc.value) + eval(sec80EESysCalc.value) +
			eval(sec80GSysCalc.value) +
			eval(sec80GGCSysCalc.value)+ eval(sec80USysCalc.value)+ eval(sec80CCGSysCalc.value)+ eval(sec80RRBSysCalc.value)+ 
			eval(sec80QQBSysCalc.value)+ eval(sec80TTASysCalc.value);
			

var grossTotInc = document.getElementsByName('partBTI.grossTotalIncome')[0]; 
var incChrgable=document.getElementsByName('partBTI.incChargeTaxSplRate111A112')[0];
var gtiLimit=eval(parseInt(coalesce(grossTotInc.value),10)-parseInt(coalesce(incChrgable.value),10));
if(gtiLimit<0){
	gtiLimit=0;
}
if(coalesce(grossTotInc.value) > parseInt('0',10)){
	if( temp2 >  parseInt(coalesce(gtiLimit) ,10)){
		dedVIA.value = parseInt(coalesce(gtiLimit) ,10);
	} else{
		dedVIA.value = temp2;
	}
}else{
	dedVIA.value = temp2;
}

var totInc = document.getElementsByName('partBTI.totalIncome')[0];
totInc.value = eval(parseInt(coalesce(grossTotInc.value) ,10) - parseInt(coalesce(dedVIA.value) ,10));
}

//To calculate Total 80G Deductions
function calcTotal80GDeductions (tableId,noOfRow,last,amt5BBC,amt5Ea)  {
	 try {

		 	var grossTotalIncome = coalesce(document.getElementsByName('partBTI.grossTotalIncome')[0].value);
		 	var incChrgable= coalesce(document.getElementsByName('partBTI.incChargeTaxSplRate111A112')[0].value);
			var status = document.getElementsByName('partAGEN1.personalInfo.status')[0].value;
			var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value;
		 	
		 	if(parseInt(grossTotalIncome ,10)< 0){
		 		
		 		grossTotalIncome='0';
		 		
		 	}
		 	
		 	var residue50Perc;
		
			var scheduleVIA =  document.getElementsByName('scheduleVIA.deductUndChapVIA.totalChapVIADeductions')[0]; scheduleVIA.value = coalesce(scheduleVIA.value);
			var schedule80G=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80G')[0]; schedule80G.value = coalesce(schedule80G.value);
			var schedule80GG=document.getElementsByName('scheduleVIA.deductUndChapVIA.section80GG')[0]; schedule80GG.value = coalesce(schedule80GG.value);
			var usr80GG=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80GG')[0]; 
			usr80GG.value = coalesce(usr80GG.value);

			var deductionsSysTotal=0;
		
			if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && (status == 'I')) {
			deductionsSysTotal=eval(parseInt(scheduleVIA.value,10)-parseInt(schedule80G.value,10)-parseInt(schedule80GG.value,10)+parseInt(usr80GG.value ,10));
			} else{
			deductionsSysTotal=eval(parseInt(scheduleVIA.value,10)-parseInt(schedule80G.value,10)-parseInt(schedule80GG.value,10));
			}
			
			if(parseInt(deductionsSysTotal ,10)> parseInt(grossTotalIncome ,10)){
				
				deductionsSysTotal=grossTotalIncome;
			}
		
			var gtiLimit=eval(parseInt(coalesce(grossTotalIncome),10)-parseInt(coalesce(incChrgable),10)) ;
			
			if(gtiLimit<0){
				gtiLimit=0;
			}
			
			var tab = document.getElementById(tableId);
			var allInputTags = tab.getElementsByTagName('input');

			if ( tableId == 'ded100PerWithoutQual' ) {
				for(var i = 0; i < allInputTags.length; i++) {
					if (allInputTags[i].name.match("eligibleDonationAmt$")) {					
						allInputTags[i].value = coalesce(allInputTags[i - 1].value);
							if( parseInt(allInputTags[i].value,10) > parseInt(grossTotalIncome ,10)) {
								allInputTags[i].value = grossTotalIncome;
							}					
					}
				}
				calcTableTotEligAmt('ded100PerWithoutQual',qualifyingLimit,residue50Perc);
			}

			if ( tableId == 'ded50WithoutQual' ) {
				for(var i = 0; i < allInputTags.length; i++) {
					if (allInputTags[i].name.match("eligibleDonationAmt$")) {
		
						allInputTags[i].value = parseInt(Math.round(coalesce(allInputTags[i - 1].value)/2) , 10);
							if( parseInt(allInputTags[i].value ,10) > parseInt(grossTotalIncome ,10) ) {
								allInputTags[i].value = grossTotalIncome;
							}
						
					}
				}
				calcTableTotEligAmt('ded50WithoutQual',qualifyingLimit,residue50Perc);
			}


			//Net Qualifyin Limit calculation

			
			var adjstGTI;
			if(grossTotalIncome == eval(parseInt(scheduleVIA.value,10) - parseInt(schedule80G.value ,10))){
				adjstGTI=0;
			}else{

				 adjstGTI = eval(parseInt(grossTotalIncome,10))-eval(parseInt(deductionsSysTotal,10))
		 			-eval(incChrgable) 
		 			+ parseInt(document.getElementsByName('scheduleSI.splCodeRateTax[0].splRateInc')[0].value)
		 			+ parseInt(coalesce(amt5BBC))
		 			+ parseInt(coalesce(amt5Ea));
				}

			
			var qualifyingLimit = eval(parseInt(adjstGTI ,10) * parseFloat('0.10'));
			

			if(parseInt(qualifyingLimit,10) <0){
				qualifyingLimit='0';
			}
			var totEligAmtTableC = document.getElementsByName('schedule80G.don100PercentApprReqd.totEligibleDon100PercentApprReqd')[0]; 

			if ( tableId == 'ded100Qual' ) {
				for(var i = 0; i < allInputTags.length; i++) {
					if (allInputTags[i].name.match("eligibleDonationAmt$")) {
						
						
						
					
						allInputTags[i].value = parseInt(Math.round(coalesce(allInputTags[i - 1].value)) , 10);
							if( parseInt(allInputTags[i].value ,10) > parseInt(qualifyingLimit , 10)) {
								allInputTags[i].value = parseInt(qualifyingLimit , 10);
							}
							
						
						
					}
				}
				calcTableTotEligAmt('ded100Qual',qualifyingLimit,residue50Perc);
			}

		
			var residue;
			if(parseInt(qualifyingLimit , 10) > parseInt(coalesce(totEligAmtTableC.value) , 10)) {

					residue = eval(parseInt(qualifyingLimit , 10)) -eval( parseInt(totEligAmtTableC.value , 10) );
				} else {
					residue = parseInt('0' ,10) ;
				}


			 residue50Perc = eval( parseInt(residue , 10) * parseFloat( '0.50' ));

			
			if ( tableId == 'ded50WithQual' ) {
				for(var i = 0; i < allInputTags.length; i++) {
					if (allInputTags[i].name.match("eligibleDonationAmt$")) {
						
					
						
						allInputTags[i].value = parseInt(Math.round(coalesce(allInputTags[i - 1].value)/2) , 10);
							if( parseInt(allInputTags[i].value ,10) > parseInt(residue50Perc , 10)) {
								allInputTags[i].value = parseInt(residue50Perc , 10);
						
							
						
						}
					}
				}
				calcTableTotEligAmt('ded50WithQual',qualifyingLimit,residue50Perc);
			}


		}
		catch (e) {
			alert('Exception in calcTotal80GDeductions method ::'+e.stack);
		}

	}

//to calculate Table Total Eligible Amount
	function calcTableTotEligAmt(tableId,qualifyingLimit,residue50Perc){
	try{

			var tab = document.getElementById(tableId);
			var allInputTags = tab.getElementsByTagName('input');
			var sumOfAll = parseInt('0' ,10);
			var sumOfAlluserEntredValue = parseInt('0' ,10);
				for(var i = 0; i < allInputTags.length; i++) {
					if (allInputTags[i].name.match("eligibleDonationAmt$")) {
						sumOfAll = eval ( parseInt(sumOfAll ,10) + parseInt( allInputTags[i].value ,10) );
						sumOfAlluserEntredValue = eval ( parseInt(sumOfAlluserEntredValue ,10) + parseInt( coalesce(allInputTags[i-1].value) ,10) );
					}
				}
			

			var grossTotalIncome = coalesce(document.getElementsByName('partBTI.grossTotalIncome')[0].value);
			
			if(parseInt(grossTotalIncome ,10)< 0){
		 		
		 		grossTotalIncome='0';
		 		
		 	}
			
			if( parseInt(sumOfAll ,10) > parseInt(grossTotalIncome ,10)) {
				sumOfAll = grossTotalIncome;
			}

		
			
			if(tableId == 'ded100PerWithoutQual'){
					var temp1 = document.getElementsByName('schedule80G.don100Percent.totEligibleDon100Percent')[0] ;
					var temp2 = document.getElementsByName('schedule80G.don100Percent.totDon100Percent')[0] ;

					temp1.value = parseInt(sumOfAll ,10);

					temp2.value = parseInt(sumOfAlluserEntredValue ,10);
					
					
				}
			else if(tableId == 'ded50WithoutQual'){
					var temp1 = document.getElementsByName('schedule80G.don50PercentNoApprReqd.totEligibleDon50Percent')[0] ;
					var temp2 = document.getElementsByName('schedule80G.don50PercentNoApprReqd.totDon50PercentNoApprReqd')[0] ;
					temp1.value = parseInt(sumOfAll ,10);
					temp2.value = parseInt(sumOfAlluserEntredValue ,10);
				}
			else if(tableId == 'ded100Qual'){
					var temp1 = document.getElementsByName('schedule80G.don100PercentApprReqd.totEligibleDon100PercentApprReqd')[0] ;
					var temp2 = document.getElementsByName('schedule80G.don100PercentApprReqd.totDon100PercentApprReqd')[0] ;
					temp1.value = parseInt(sumOfAll ,10);
					temp2.value = parseInt(sumOfAlluserEntredValue ,10);
					
					if(parseInt(temp1.value ,10) > parseInt(qualifyingLimit ,10)){
						
						temp1.value=parseInt(qualifyingLimit ,10);;
					}
					
			}
			else if(tableId == 'ded50WithQual'){

					var temp1 = document.getElementsByName('schedule80G.don50PercentApprReqd.totEligibleDon50PercentApprReqd')[0] ;
					var temp2 = document.getElementsByName('schedule80G.don50PercentApprReqd.totDon50PercentApprReqd')[0] ;

					temp1.value = parseInt(sumOfAll ,10);
					temp2.value = parseInt(sumOfAlluserEntredValue ,10);
					
					if(parseInt(temp1.value ,10) > parseInt(residue50Perc ,10)){
						
						temp1.value=parseInt(residue50Perc ,10);;
					}

			}

			calcTotalDonations80G();
			calcEligbDonations80G();
	}catch(e){
		alert('Exception in calcTableTotEligAmt :'+e.stack);
	}
	}

//To calculate Total Donations in schedule 80G
function calcTotalDonations80G(){

		 var tot80GAuserEntrd =  document.getElementsByName('schedule80G.don100Percent.totDon100Percent')[0]; tot80GAuserEntrd.value = coalesce(tot80GAuserEntrd.value);
		 var tot80GBuserEntrd =  document.getElementsByName('schedule80G.don50PercentNoApprReqd.totDon50PercentNoApprReqd')[0]; tot80GBuserEntrd.value = coalesce(tot80GBuserEntrd.value);
		 var tot80GCuserEntrd =  document.getElementsByName('schedule80G.don100PercentApprReqd.totDon100PercentApprReqd')[0]; tot80GCuserEntrd.value = coalesce(tot80GCuserEntrd.value);
		 var tot80GDuserEntrd =  document.getElementsByName('schedule80G.don50PercentApprReqd.totDon50PercentApprReqd')[0]; tot80GDuserEntrd.value = coalesce(tot80GDuserEntrd.value);
		 var tot80GDonuserEntrd =  document.getElementsByName('schedule80G.totalDonationsUs80G')[0]; tot80GDonuserEntrd.value = coalesce(tot80GDonuserEntrd.value);

		 tot80GDonuserEntrd.value = eval(tot80GAuserEntrd.value)+ eval(tot80GBuserEntrd.value)+ eval(tot80GCuserEntrd.value)+ eval(tot80GDuserEntrd.value) ;

}

//To calculate EligbDonations80G
function calcEligbDonations80G(){
	var grossTotalIncome = coalesce(document.getElementsByName('partBTI.grossTotalIncome')[0].value);
	var incChrgable= coalesce(document.getElementsByName('partBTI.incChargeTaxSplRate111A112')[0].value); 
	var gtiLimit=eval(parseInt(coalesce(grossTotalIncome),10)-parseInt(coalesce(incChrgable),10)) ;
	
		 var tot80GAelig =  document.getElementsByName('schedule80G.don100Percent.totEligibleDon100Percent')[0]; tot80GAelig.value = coalesce(tot80GAelig.value);
		 var tot80GBelig =  document.getElementsByName('schedule80G.don50PercentNoApprReqd.totEligibleDon50Percent')[0]; tot80GBelig.value = coalesce(tot80GBelig.value);
		 var tot80GCelig =  document.getElementsByName('schedule80G.don100PercentApprReqd.totEligibleDon100PercentApprReqd')[0]; tot80GCelig.value = coalesce(tot80GCelig.value);
		 var tot80GDelig =  document.getElementsByName('schedule80G.don50PercentApprReqd.totEligibleDon50PercentApprReqd')[0]; tot80GDelig.value = coalesce(tot80GDelig.value);
		 var tot80GDonelig =  document.getElementsByName('schedule80G.totalEligibleDonationsUs80G')[0]; tot80GDonelig.value = coalesce(tot80GDonelig.value);

		 tot80GDonelig.value = eval(tot80GAelig.value)+ eval(tot80GBelig.value)+ eval(tot80GCelig.value)+ eval(tot80GDelig.value) ;

		 if(tot80GDonelig.value> gtiLimit){
			 tot80GDonelig.value=gtiLimit;
		 }
}

//To enable Schedule 80GG
function enable80GG(){
	
	var status=document.getElementsByName('partAGEN1.personalInfo.status')[0].value;
	var sec80GG=document.getElementsByName('scheduleVIA.usrDeductUndChapVIA.section80GG')[0];
	
	if(status=='I'){
		sec80GG.disabled=false;
		sec80GG.readOnly=false;
		
	}else 
	{
	if(status=='H'){		
		sec80GG.disabled=true;
		sec80GG.readOnly=true;
		sec80GG.value="";
		document.getElementsByName('scheduleVIA.deductUndChapVIA.section80GG')[0].value="";
	}
}	
}

//To calculate Age
function calcAge(){
	var dob = document.getElementsByName('partAGEN1.personalInfo.dob')[0];
	var retVal = calcAgeCommon201516(dob);
	return retVal;
}

//To calculate Schedule CG Deductions
function calculateCGDeductions(){
	var tab = document.getElementById('schduleCGDed');
	var inputs = tab.getElementsByTagName('INPUT');
	var sum = 0;
	for(var i=0; i<inputs.length; i++){
		if(inputs[i].name.match('amtDed$')){
			sum = parseInt(sum, 10) + parseInt(coalesce(inputs[i].value), 10);
		}
	}
	var totDeductClaim = document.getElementsByName('scheduleCGPost45.deducClaimInfo.totDeductClaim')[0];
	totDeductClaim.value = sum;
}

//To calculate sch CG
function calcSchCG(cgosIncome){
	try{

		calculateSTCG(cgosIncome);
		calculateLTCG(cgosIncome);
		
		var totScheduleCGPost45 = document.getElementsByName('scheduleCGPost45.totScheduleCGPost45')[0];
		totScheduleCGPost45.value = eval(coalesceSetRet('scheduleCGPost45.shortTermCapGainPost45.totalSTCG') +
										 parseInt(zeroOrMore(coalesceSetRet('scheduleCGPost45.longTermCapGainPost45.totalLTCG'))));
		
		calculateCGDeductions();
		
		doCGSetOff(cgosIncome);

		
	}catch(e){
		alert('Exception in calcSchCG method ' + e.stack);
	}
}

//To add row to CG
function addRowToCG(tableId){
	var tab = document.getElementById(tableId);
	var body = tab.tBodies[0];
	var clone = body.cloneNode(true);
	var index = parseInt(tab.tBodies.length,10) + 1;
	clone.rows[0].cells[0].innerHTML = index;
	var inputs = clone.getElementsByTagName('INPUT');
	for(var i=0;i<inputs.length;i++){
		inputs[i].name = inputs[i].name.replace(/\[[\d]+\]/, '[' + (index-1) + ']');
		inputs[i].value = '';
		var blurAttr=inputs[i].getAttribute('onblur');
		if(blurAttr!=null){
			blurAttr=blurAttr+";";
		}else{
			blurAttr="";
		}		
		inputs[i].setAttribute('onblur',blurAttr+'j.blur(this,this.name,this.value);');
	}
	var selects = clone.getElementsByTagName('SELECT');
	for(var i=0;i<selects.length;i++){
		selects[i].name = selects[i].name.replace(/\[[\d]+\]/, '[' + (index-1) + ']');
		selects[i].selectedIndex = 0;
		var blurAttr=selects[i].getAttribute('onblur');
		if(blurAttr!=null){
			blurAttr=blurAttr+";";
		}else{
			blurAttr="";
		}		
		selects[i].setAttribute('onblur',blurAttr+'j.blur(this,this.name,this.value);');
	}	
	
	if(clone.getElementsByTagName('table').length>0){
		clone.getElementsByTagName('table')[0].setAttribute('id',tableId+'_ded'+index);
		clone.getElementsByTagName('img')[0].setAttribute('onclick','addRowToTable('+'\''+tableId+'_ded'+index+'\',3,2,this);');
		clone.getElementsByTagName('img')[1].setAttribute('onclick','deleteRowTable('+'\''+tableId+'_ded'+index+'\',1,2)');
	}
	tab.appendChild(clone);
	modifyRow(tab);
	
	if(clone.getElementsByTagName('table').length>0){
		$('#'+tableId+'_ded'+index+' input').attr("checked" , true);
	    deleteRowTable(tableId+'_ded'+index,1,2);
		$('#'+tableId+'_ded'+index+' input').attr("checked" , false);
	}
}

//To delete row of CG
function deleteRowToCG(tableId){
	var tab = document.getElementById(tableId);
	var len = tab.tBodies.length;
	if(len>1){
		tab.removeChild(tab.tBodies[len-1]);
	}
	modifyRow(tab);
}

//To calculate  LTCG and STCG
function calcSchCGLtcgStcg(){

	try{
		
	var stcg15Per = coalesceSetRet("scheduleBFLA.stcg.stcg15Per.incBFLA.incOfCurYrAfterSetOffBFLosses");
	var shortTermUnder15Per = 		coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnder15Per.upto15Of9") +  
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnder15Per.up16Of9To15Of12") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnder15Per.up16Of12To15Of3") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnder15Per.up16Of3To31Of3");
	
	var stcgAppRate = coalesceSetRet("scheduleBFLA.stcg.stcgAppRate.incBFLA.incOfCurYrAfterSetOffBFLosses");
	var shortTermUnderAppRate = coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnderAppRate.upto15Of9") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnderAppRate.up16Of9To15Of12") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnderAppRate.up16Of12To15Of3") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnderAppRate.up16Of3To31Of3");

	var stcg30Per = coalesceSetRet("scheduleBFLA.stcg.stcg30Per.incBFLA.incOfCurYrAfterSetOffBFLosses");
	var shortTermUnder30Per = 	coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnder30Per.upto15Of9") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnder30Per.up16Of9To15Of12") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnder30Per.up16Of12To15Of3") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.shortTermUnder30Per.up16Of3To31Of3") ;
	
	var ltcg10Per = coalesceSetRet("scheduleBFLA.ltcg.ltcg10Per.incBFLA.incOfCurYrAfterSetOffBFLosses");
	var longTermUnder10Per = coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.longTermUnder10Per.upto15Of9") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.longTermUnder10Per.up16Of9To15Of12") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.longTermUnder10Per.up16Of12To15Of3") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.longTermUnder10Per.up16Of3To31Of3") ;

	var ltcg20Per = coalesceSetRet("scheduleBFLA.ltcg.ltcg20Per.incBFLA.incOfCurYrAfterSetOffBFLosses");
	var longTermUnder20Per = coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.longTermUnder20Per.upto15Of9") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.longTermUnder20Per.up16Of9To15Of12") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.longTermUnder20Per.up16Of12To15Of3") + 
								coalesceSetRet("scheduleCGPost45.accruOrRecOfCG.longTermUnder20Per.up16Of3To31Of3") ;	
	
	// check for STCG
	if(stcg15Per > shortTermUnder15Per) {
		j.setFieldError('scheduleCGPost45.accruOrRecOfCG.shortTermUnder15Per.upto15Of9','Total of Quarterly breakup in STCG 15% is less by ' + (stcg15Per-shortTermUnder15Per));
		addErrorXHTML('',"Total of Quarterly breakup in STCG 111A is less by " + (stcg15Per-shortTermUnder15Per));
		}
	if(stcg15Per < shortTermUnder15Per) {
		j.setFieldError('scheduleCGPost45.accruOrRecOfCG.shortTermUnder15Per.upto15Of9','Total of Quarterly breakup in STCG 15% is more by ' + Math.abs(stcg15Per-shortTermUnder15Per));
		addErrorXHTML('',"Total of Quarterly breakup in STCG 111A is more by " + Math.abs(stcg15Per-shortTermUnder15Per));
		}
	
	if(stcgAppRate > shortTermUnderAppRate) {
		j.setFieldError('scheduleCGPost45.accruOrRecOfCG.shortTermUnderAppRate.upto15Of9','Total of Quarterly breakup in STCG Applicable Rates is less by ' + (stcgAppRate-shortTermUnderAppRate));
		addErrorXHTML('',"Total of Quarterly breakup in STCG Others is less by " + (stcgAppRate-shortTermUnderAppRate));
	}
	if(stcgAppRate < shortTermUnderAppRate) {
		j.setFieldError('scheduleCGPost45.accruOrRecOfCG.shortTermUnderAppRate.upto15Of9','Total of Quarterly breakup in STCG Applicable Rates is more by ' + Math.abs(stcgAppRate-shortTermUnderAppRate));
		addErrorXHTML('',"Total of Quarterly breakup in STCG Others is more by " + Math.abs(stcgAppRate-shortTermUnderAppRate));
	}
	if(stcg30Per > shortTermUnder30Per) {
		j.setFieldError('scheduleCGPost45.accruOrRecOfCG.shortTermUnder30Per.upto15Of9', 'Total of Quarterly breakup in STCG 30% is less by ' + (stcg30Per-shortTermUnder30Per));
		addErrorXHTML('',"Total of Quarterly breakup in LTCG Proviso is less by " + (stcg30Per-shortTermUnder30Per));
	}
	if(stcg30Per < shortTermUnder30Per) {
		j.setFieldError('scheduleCGPost45.accruOrRecOfCG.shortTermUnder30Per.upto15Of9', 'Total of Quarterly breakup in STCG 30% is more by ' + (stcg30Per-shortTermUnder30Per));
		addErrorXHTML('',"Total of Quarterly breakup in LTCG Proviso is more by " + Math.abs(stcg30Per-shortTermUnder30Per));
	}
	
	// check for LTCG

	if(ltcg10Per > longTermUnder10Per)	{
		j.setFieldError('scheduleCGPost45.accruOrRecOfCG.longTermUnder10Per.upto15Of9','Total of Quarterly breakup in LTCG 10% is less by ' + (ltcg10Per-longTermUnder10Per));
		addErrorXHTML('',"Total of Quarterly breakup in LTCG Non Proviso is less by " + (ltcg10Per-longTermUnder10Per));
	}
	
	if(ltcg10Per < longTermUnder10Per)	{
		j.setFieldError('scheduleCGPost45.accruOrRecOfCG.longTermUnder10Per.upto15Of9','Total of Quarterly breakup in LTCG 10% is more by ' + Math.abs(ltcg10Per-longTermUnder10Per));
		addErrorXHTML('',"Total of Quarterly breakup in LTCG Non Proviso is more by " + Math.abs(ltcg10Per-longTermUnder10Per));
	}
	
	if(ltcg20Per > longTermUnder20Per)	{
		j.setFieldError('scheduleCGPost45.accruOrRecOfCG.longTermUnder20Per.upto15Of9','Total of Quarterly breakup in LTCG 20% is less by ' + (ltcg20Per-longTermUnder20Per));
		addErrorXHTML('',"Total of Quarterly breakup in LTCG Non Proviso is less by " + (ltcg20Per-longTermUnder20Per));
	}
	
	if(ltcg20Per < longTermUnder20Per)	{
		j.setFieldError('scheduleCGPost45.accruOrRecOfCG.longTermUnder20Per.upto15Of9','Total of Quarterly breakup in LTCG 20% is more by ' + Math.abs(ltcg20Per-longTermUnder20Per));
		addErrorXHTML('',"Total of Quarterly breakup in LTCG Non Proviso is more by " + Math.abs(ltcg20Per-longTermUnder20Per));
	}
	
	var fullConsideration = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.fullConsideration')[0];
	var propertyValuation = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.propertyValuation')[0];
	var fullConsideration50C = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.fullConsideration50C')[0];
	
	if(fullConsideration50C.value!=fullConsideration.value && fullConsideration50C.value!=propertyValuation.value){
		j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.fullConsideration50C',"Please enter value from 'ai' or 'aii' only");
		addErrorXHTML(fullConsideration50C ,"Please enter value from 'ai' or 'aii' only");
	}
	
	fullConsideration = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.fullConsideration')[0];
	propertyValuation = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.propertyValuation')[0];
	fullConsideration50C = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.fullConsideration50C')[0];
	
	if(fullConsideration50C.value!=fullConsideration.value && fullConsideration50C.value!=propertyValuation.value){
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.fullConsideration50C',"Please enter value from 'ai' or 'aii' only");
		addErrorXHTML(fullConsideration50C ,"Please enter value from 'ai' or 'aii' only");
	}	
	
	var tab = document.getElementById('stcg10pctTab');
	var selects = tab.getElementsByTagName("SELECT");
	var count = {"21ciii": 0,"5AC1c": 0,"5ADiii": 0,"5ACA1b": 0};
	for(var i=0;i<selects.length;i++){
		count[selects[i].value] = count[selects[i].value]+1;
		if(count[selects[i].value] > 1){
			j.setFieldError(selects[i].name,' A particular drop down cannot be selected twice');
			addErrorXHTML(selects[i] ," A particular drop down cannot be selected twice");
			break;
		}
	}
	}catch(e){
		alert('Exception in calcSchCGLtcgStcg method ' + e.stack);
	}
}	

//To calculate OS
function calculateOS(cgosIncome){
	
	var simap = [];
	
	coalesceSetRet('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls[0].sourceAmount');
	
	var othersGross = document.getElementsByName('scheduleOS.othersGross')[0];
	othersGross.value = calculateOSGross(simap);
	validateSchOSDTAA1a1b();
	
	var totalOSGross = document.getElementsByName('scheduleOS.totalOSGross')[0];
	totalOSGross.value = eval(
			parseInt(coalesceSetRet('scheduleOS.incOthThanOwnRaceHorse.dividendGross'),10)
			+ parseInt(coalesceSetRet('scheduleOS.incOthThanOwnRaceHorse.interestGross'),10)
			+ parseInt(coalesceSetRet('scheduleOS.incOthThanOwnRaceHorse.rentFromMachPlantBldgs'),10)
			+ parseInt(coalesceSetRet('scheduleOS.othersGross'),10)
		);
	
	var totAmtUnderDtaa = document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa.totAmtUnderDtaa')[0];
	totAmtUnderDtaa.value = addCGDeductions('scheduleOsNriIncTaxDtaa');
	
	var totalOSGrossChargblSplRate = document.getElementsByName('scheduleOS.incChargblSplRateOS.totalOSGrossChargblSplRate')[0];
	totalOSGrossChargblSplRate.value = eval(
			parseInt(coalesceSetRet('scheduleOS.incChargblSplRateOS.winningFrmLotteries'),10)
			+ parseInt(coalesceSetRet('scheduleOS.incChargblSplRateOS.secXIIOth'),10)
			+ parseInt(coalesceSetRet('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa.totAmtUnderDtaa'),10)
		);
	
	var grossAmtChargblNormalRate = document.getElementsByName('scheduleOS.grossAmtChargblNormalRate')[0];
	grossAmtChargblNormalRate.value = eval(
			parseInt(totalOSGross.value,10)
			- parseInt(totalOSGrossChargblSplRate.value,10)
		);
	
	var totDeductions = document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.deductions.totDeductions')[0];
	totDeductions.value = eval(
			parseInt(coalesceSetRet('scheduleOS.incOthThanOwnRaceHorse.deductions.expenses'),10)
			+ parseInt(coalesceSetRet('scheduleOS.incOthThanOwnRaceHorse.deductions.depreciation'),10)
		);	
	
	var balanceNoRaceHorse = document.getElementsByName('scheduleOS.balanceNoRaceHorse')[0];
    
	balanceNoRaceHorse.value = eval(
			parseInt(grossAmtChargblNormalRate.value,10)
			- parseInt(totDeductions.value,10)
		);
                    
	var totOthSrcNoRaceHorse = document.getElementsByName('scheduleOS.totOthSrcNoRaceHorse')[0];
	var IncmOthrSrc = document.getElementsByName('scheduleOS.balanceNoRaceHorse')[0];
     
	totOthSrcNoRaceHorse.value = eval(
			parseInt(totalOSGrossChargblSplRate.value,10)
			+ parseInt(zeroOrMore(parseInt(IncmOthrSrc.value,10)))
		);
	
	var balanceOwnRaceHorse = document.getElementsByName('scheduleOS.incFromOwnHorse.balanceOwnRaceHorse')[0];
	balanceOwnRaceHorse.value = eval(
			parseInt(coalesceSetRet('scheduleOS.incFromOwnHorse.receipts'),10)
			- parseInt(coalesceSetRet('scheduleOS.incFromOwnHorse.deductSec57'),10)
		);
	
	var incChargeable = document.getElementsByName('scheduleOS.incChargeable')[0];
	incChargeable.value = eval(
			parseInt(totOthSrcNoRaceHorse.value,10)
			+ parseInt(zeroOrMore(parseInt(balanceOwnRaceHorse.value ,10)))
		);
	return simap;
}

function validateSchOSDTAA1a1b() {
	var dividendGross = parseInt(coalesce(document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.dividendGross')[0].value),10);
	var interestGross = parseInt(coalesce(document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.interestGross')[0].value),10);
	
	var table = document.getElementById('scheduleOsNriIncTaxDtaa');
	var rowCount = table.rows.length - 2;
	
	var dividendGrossTot = parseInt('0',10);
	var interestGrossTot = parseInt('0',10);
	
	for(var k=0; k<rowCount; k++) {
		if(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].itemIncluded')[0].value == '56i') {
			dividendGrossTot = eval(dividendGrossTot + parseInt(coalesce(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].amount')[0].value),10));
			if(eval(dividendGrossTot > dividendGross)) {
				if (document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+ k + '].amount')[0].value != '') {
					document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+ k + '].amount')[0].value = 0;
					addErrorXHTML(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+ k + '].amount')[0],'For Dividend - The sum of amount should not exceed amount entered in 1a.',true);
					j.setFieldError('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+ k + '].amount','For Dividend - The sum of amount should not exceed amount entered in 1a.');
				}
			}
		} else if (document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].itemIncluded')[0].value == '56') {
			interestGrossTot = eval(interestGrossTot + parseInt(coalesce(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].amount')[0].value),10));
			if(eval(interestGrossTot > interestGross)) {
				if (document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+ k + '].amount')[0].value != '') {
					document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+ k + '].amount')[0].value = 0;
					addErrorXHTML(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+ k + '].amount')[0],'For Interest - The sum of amount should not exceed amount entered in 1b.',true);
					j.setFieldError('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+ k + '].amount','For Interest - The sum of amount should not exceed amount entered in 1b.');
				}
			}
		}		
	}
	
}

//To calculate gross OS
function calculateOSGross(simap){
	try{
	var total = parseInt('0' ,10);
	var tabl = document.getElementById('schduleOsf');
	var allInputTags = tabl.getElementsByTagName('input');
	for(var i = 0; i < allInputTags.length; i++) {
			if (allInputTags[i].name.match("sourceAmount$")) {
					total = eval(parseInt(total ,10) + parseInt(isNVL(allInputTags[i].value) ,10));
			}			
		}
	var allSelects = tabl.getElementsByTagName('SELECT'); 
	
	var table = document.getElementById('scheduleOsNriIncTaxDtaa');
	var rowCount = table.rows.length - 2;
	var arr = {'5A1ai':0,'5A1aii':0,'5A1aiia':0,'5A1aiiaa':0,'5A1aiiab':0,'5A1aiiac':0,'5A1aiii':0,'5A1bA':0,'5A1bB':0,'5AC1ab':0,'5BBA':0,'5Ea':0};
	var sum = 0;
	for(var i = 0; i < allSelects.length; i++) {	
			var name = allSelects[i].name;
			var index = name.substring(name.indexOf('[')+1, name.indexOf(']'));
			if(allSelects[i].value=='Others'){
				document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].otherDesc')[0].style.display='';
			}
			else{
				simap[allSelects[i].value] = coalesce(document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ i +'].sourceAmount')[0].value);			
				document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].otherDesc')[0].style.display='none';
				document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].otherDesc')[0].value='';
				if(allSelects[i].value=='5BB'){
					var winningFrmLotteries = document.getElementsByName('scheduleOS.incChargblSplRateOS.winningFrmLotteries')[0];
					winningFrmLotteries.value = document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].sourceAmount')[0].value;
				} else if(allSelects[i].value != 'DTAA'){
					sum = parseInt(sum) + parseInt(coalesce(document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].sourceAmount')[0].value));
					for(var k=0; k<rowCount; k++) {
						if(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].itemIncluded')[0].value == allSelects[i].value) {
							arr[allSelects[i].value] = eval(parseInt(coalesce(arr[allSelects[i].value])) + parseInt(coalesce(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].amount')[0].value)));
							if(arr[allSelects[i].value] > parseInt(coalesce(document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].sourceAmount')[0].value))) {
								
								if(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].amount')[0].value != '') {
									document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].amount')[0].value = 0;
									addErrorXHTML(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].amount')[0]  ,'The sum of amount should not exceed amount entered in 1d.',true);
									j.setFieldError('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].amount','The sum of amount should not exceed amount entered in 1d.');
								}
							} else {
								sum -=  document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].amount')[0].value;
							}
					}
				}
					simap[allSelects[i].value] -= parseInt(coalesce(arr[allSelects[i].value]),10);
			}
		}
	}
	
	var secXIIOth = document.getElementsByName('scheduleOS.incChargblSplRateOS.secXIIOth')[0];
	secXIIOth.value = sum;
	} catch(e) {
		alert('Exception in calculateOSGross : '+e);
	}
	return total;
}

//To check dropdown selected in Schedule OS
function checkDropdownSelectedin1d() {
	var table = document.getElementById('scheduleOsNriIncTaxDtaa');
	var rowCount = table.rows.length - 2;
	var itemIncluded = [];
	
	var tabl = document.getElementById('schduleOsf');
	var rowCountTab1 = tabl.rows.length - 3;
	var sourceDescriptionMap = [];
	
	for(var i=0; i<rowCount; i++) {
		var section = document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+i+'].itemIncluded')[0];
		if(section.value != '' && section.value != '56i' && section.value != '56' && itemIncluded.indexOf(section.value) == -1) {
			itemIncluded.push(section.value);
		}
	}
	
	for(var i=1; i<rowCountTab1; i++) {
		var sourceDescription = document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+i+'].sourceDescription')[0];
		
		if(sourceDescription.value != '' && sourceDescriptionMap.indexOf(sourceDescription.value) == -1) {
			sourceDescriptionMap.push(sourceDescription.value);
		}
	}
	var index = 0;
	for(var i=0; i<itemIncluded.length; i++) {
		if(sourceDescriptionMap.indexOf(itemIncluded[i]) == -1) {
			for(var k=0; k<rowCount; k++) {
				var section = document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+k+'].itemIncluded')[0];
				if(section.value != '' && section.value == itemIncluded[i] ) {
					index = k;
				}
			}
			addErrorXHTML(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+index+'].itemIncluded')[0]  ,'Please select this section in table 1d.',true);
			j.setFieldError('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa['+index+'].itemIncluded','Please select this section in table 1d.');
		}
	}
}

//To validate Pan status
function validatePanStatus(){
	var status = document.getElementsByName('partAGEN1.personalInfo.status')[0].value;
	var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value;

	if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && (status == 'H')){

		addErrorXHTML(document.getElementsByName('partAGEN1.personalInfo.status')[0] ,'Since PAN entered is Individual PAN, Select Status as Individual',true);	
		j.setFieldError('partAGEN1.personalInfo.status','Since PAN entered is Individual PAN, Select Status as Individual');
		
	} else if((pan.substring(3,4)=='H' || pan.substring(3,4)=='h') && (status == 'I')){
		
		addErrorXHTML(document.getElementsByName('partAGEN1.personalInfo.status')[0] ,'Since PAN entered is HUF PAN, Select Status as HUF',true);	
		j.setFieldError('partAGEN1.personalInfo.status','Since PAN entered is HUF PAN, Select Status as HUF');
}
	
}

//To set Aadhar option
function setAadharOption() {
	var status = document.getElementsByName('partAGEN1.personalInfo.status')[0].value;
	var aadhar = document.getElementsByName('partAGEN1.personalInfo.adharNoOption')[0];

	if (status == 'I') {
		removeAll(aadhar);
		addOption(aadhar, 'Yes', 'Y');
		addOption(aadhar, 'No', 'N');
	} else if (status == 'H') {
		removeAll(aadhar);
		addOption(aadhar, 'NA', 'X');
	} else {

		removeAll(aadhar);
		addOption(aadhar, 'Yes', 'Y');
		addOption(aadhar, 'No', 'N');
		addOption(aadhar, 'NA', 'X');

	}
}

//To remove section
function removeSection(sectionArray, rowCount) {
  try{
	for (var i=1; i<rowCount;  i++) {
	var selectsLength = document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+i+'].sourceDescription')[0].options.length;
		for (var k=selectsLength; k>0;  k--) {
      		   if(document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+i+'].sourceDescription')[0].options[k] != null && sectionArray.indexOf(document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+i+'].sourceDescription')[0].options[k].value) != -1) {
			   document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+i+'].sourceDescription')[0].remove(k);
		   }
		}
	}
  } catch(e) {
    alert('Exception in removeSection method:'+e.stack);
  }
}

//To add all options in schedule OS
function addAllOptions(allSectionArray, rowCount) {
	for (var i=1; i<rowCount;  i++) {
		var srcDesc = document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+i+'].sourceDescription')[0];
		var selectedValue = srcDesc.value;
		removeAll(srcDesc);
		for(var k=0; k<allSectionArray.length; k++) {
			var optn = document.createElement("option");
			optn.text = getSectionTextMap(allSectionArray[k]);
			optn.value = allSectionArray[k];
			srcDesc.options.add(optn);
		}
		srcDesc.value = selectedValue;
	}
}

//To set other gross in Schedule OS
function setOtherGrossSource() {
	var status = document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value;
	
	var tab = document.getElementById('schduleOsf');
	var rowCount= tab.rows.length - 3;
	
	var allSectionArray = ['5A1ai','5A1aii','5A1aiia','5A1aiiaa','5A1aiiab','5A1aiiac','5A1aiii','5A1bA','5A1bB','5AC1ab','5ACA1a','5AD1i','5AD1iP','5BBA','5BBC','5BBE','5Ea','1','Others'];
	
	if (status == 'RES' || status=='NOR') {
		addAllOptions(allSectionArray,rowCount);
		var sectionArray = ['5A1ai','5A1aii','5A1aiia','5A1aiiaa','5A1aiiab','5A1aiiac','5A1aiii','5A1bA','5A1bB','5AC1ab','5BBA'];
		removeSection(sectionArray, rowCount);
	} else if (status == 'NRI') {
		addAllOptions(allSectionArray,rowCount);
		var sectionArray = ['5ACA1a'];
		removeSection(sectionArray, rowCount);
	}
}

//To add options dynamically
function addOption(selectbox, text, value) {
	var optn = document.createElement("option");
	optn.text = text;
	optn.value = value;
	selectbox.options.add(optn);
}

//To delete all options from the dropdown
function removeAll(selectbox) {

	for ( var i = selectbox.options.length - 1; i > 0; i--) {
		selectbox.removeChild(selectbox[i]);

	}
}

//To set aadhar options on load
function setAadharOptionOnLoad() {
	var aadhar = document.getElementsByName('partAGEN1.personalInfo.adharNoOption')[0].value;
	setAadharOption();
	document.getElementsByName('partAGEN1.personalInfo.adharNoOption')[0].value = aadhar;

}


//To set the country value On state change
function onStateChng(){
	try{
		var state = document.getElementsByName('partAGEN1.personalInfo.address.stateCode')[0];
		var country = document.getElementsByName('partAGEN1.personalInfo.address.country')[0];
		var pinCode = document.getElementsByName('partAGEN1.personalInfo.address.pinCode')[0];
		
		if(state.value != '99' && state.value != '-1'){
			country.value='91';
			pinCode.value='';
		}else if(state.value == '99'){
			pinCode.value='999999';
		}
	}catch(e){
		alert('Exception in onStateChng method::'+e.stack);
	}	
}

//To enable or disable revised field
function revisedSetFor6OnLoad(section,type){

    var fileSec=document.getElementsByName(section)[0].value;
    var fileType=document.getElementsByName(type)[0];

	if(fileSec=='17' && fileType.value!='R'){

		document.getElementsByName(type)[0].value='R';
		
		document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=false;
		document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=false;

		document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].value='';
		document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].disabled=true;
		
       }
	   
	   else if(fileSec=='18'){
	   document.getElementsByName(type)[0].value='O';
			document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=false;
			document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=false;
	   
	   }
       else if(fileSec !='17' || fileType.value!='R'){
		   document.getElementsByName(type)[0].value='O';
			document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=true;
			document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=true;
       }
           if(fileSec=='18') {
               document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].disabled=false;
				document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=false;
				document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=false;
           } else {
               document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].value='';
               document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].disabled=true;


           }
		   if(fileSec=='13' || fileSec=='14' || fileSec=='15' || fileSec=='16' || fileSec=='18'){
		      enableField('partAGEN1.filingStatus.returnFileSec',fileSec,
		'partAGEN1.filingStatus.noticeDateUnderSec'
		);
		   }else{
		   document.getElementsByName("partAGEN1.filingStatus.noticeDateUnderSec")[0].value='';
               document.getElementsByName("partAGEN1.filingStatus.noticeDateUnderSec")[0].disabled=true;
		   }
}

function revisedSetFor6(section,type){

    var fileSec=document.getElementsByName(section)[0].value;
    var fileType=document.getElementsByName(type)[0];

	if(fileSec=='17' && fileType.value!='R'){

		document.getElementsByName(type)[0].value='R';
		document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].value='';
		document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].value='';
		document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=false;
		document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=false;

		document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].value='';
		document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].disabled=true;
		
       }
	   
	   else if(fileSec=='18'){
	   document.getElementsByName(type)[0].value='O';
	        document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].value='';
		    document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].value='';
			document.getElementsByName("partAGEN1.filingStatus.noticeDateUnderSec")[0].value='';
			document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=false;
			document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=false;
			document.getElementsByName("partAGEN1.filingStatus.noticeDateUnderSec")[0].disabled=false;
	   
	   }
       else if(fileSec !='17' || fileType.value!='R'){
		   document.getElementsByName(type)[0].value='O';
			document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=true;
			document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=true;
       }
           if(fileSec=='18') {
               document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].disabled=false;
				document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=false;
				document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=false;
           } else {
               document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].value='';
               document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].disabled=true;


           }
		   if(fileSec=='13' || fileSec=='14' || fileSec=='15' || fileSec=='16' || fileSec=='18'){
		      enableField('partAGEN1.filingStatus.returnFileSec',fileSec,
		'partAGEN1.filingStatus.noticeDateUnderSec'
		);
		   }else{
		   document.getElementsByName("partAGEN1.filingStatus.noticeDateUnderSec")[0].value='';
               document.getElementsByName("partAGEN1.filingStatus.noticeDateUnderSec")[0].disabled=true;
		   }
		   if(fileSec=='11' || fileSec=='12' || fileSec=='13' || fileSec=='14' || fileSec=='15' || fileSec=='16' || fileSec=='20'){
		   document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].value='';
		    document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].value='';
			document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].value='';
            document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].disabled=true;
			document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=true;
			document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=true;
		   
		   }
}

//To display 92CD Verification value
function display92CDVerification() {
	var fileSec=document.getElementsByName('partAGEN1.filingStatus.returnFileSec')[0].value;
	
	if(fileSec == '20'){
		addErrorXHTML('','To file return u/s 119(2)(b), post login in e-Filing portal, go to "e-File" --> "Income Tax Return" and select the applicable AY, ITR and other options.');
	}
}

function sectionSetFor6(section,type){
    var fileSec = document.getElementsByName(section)[0];
    var fileType=document.getElementsByName(type)[0].value;

        if(fileType=='R' && fileSec.value!=17){
            fileSec.value='17';
        }
        else {
            fileSec.value='';
        }
            if(fileType=='R') {
                document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=false;
                document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=false;
                document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].value='';
                document.getElementsByName("partAGEN1.filingStatus.noticeNo")[0].disabled=true;
            } else {
                document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].value='';
                document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].value='';
                document.getElementsByName("partAGEN1.filingStatus.receiptNo")[0].disabled=true;
                document.getElementsByName("partAGEN1.filingStatus.origRetFiledDate")[0].disabled=true;

            }
}

//On Status Change enable fields
function onStatusChange(){
	var gender = document.getElementsByName('partAGEN1.personalInfo.gender')[0];
	var status = document.getElementsByName('partAGEN1.personalInfo.status')[0];
	
	enableField('partAGEN1.personalInfo.status','I','partAGEN1.personalInfo.passportNumber');
	
	if(status.value == 'I' || status.value == ''){
		if(gender.value=='X') {
			gender.options[0].selected = true;
		}
            document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].disabled=false;
	}else if(status.value == 'H'){
		gender.options[3].selected = true;
		document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].value='';
                 document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].disabled=true;
	}
	onChngPCC5A();disableSchedule5A();
}

//On gender Change enable fields
function onGenderChange(){
	var gender = document.getElementsByName('partAGEN1.personalInfo.gender')[0];
	var status = document.getElementsByName('partAGEN1.personalInfo.status')[0];
	if(gender.value == 'X'){
		status.options[2].selected = true;
                document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].disabled=true;
	}else if(gender.value == 'F' || gender.value == 'M'){
		status.options[1].selected = true;
                document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].disabled=false;
                document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].value='';
	}else{
            document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].disabled=false;
            document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].value='';
        }
}

//On load enable or disable fields
function adjustForm(){
		enableField('partAGEN1.filingStatus.asseseeRepFlg','Y',
		'partAGEN1.filingStatus.assesseeRep.repName',
		'partAGEN1.filingStatus.assesseeRep.repAddress',
		'partAGEN1.filingStatus.assesseeRep.repPAN'
		);
		
		adjustTDS2();
		adjustOS();
}

//To adjust schedule OS
function adjustOS() {
	var tabl = document.getElementById('schduleOsf');
	
	var allSelects = tabl.getElementsByTagName('SELECT');
	
	for(var i = 0; i < allSelects.length; i++) {	
			var name = allSelects[i].name;
			var index = name.substring(name.indexOf('[')+1, name.indexOf(']'));
			if(allSelects[i].value=='Others'){
				document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].otherDesc')[0].style.display='';
			} else {
				document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].otherDesc')[0].style.display='none';
				document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].otherDesc')[0].value='';
			}
	}
}

//To enable or disable schedule CG
function adjustCG() {
	
	 enableTable('scheduleCGPost45.LongTermCapGainPost45.unutilizedCapgainFlag','Y','scheduleLtcgunUtilizedCapGain54');
	 enableTableWithOutCB('scheduleCGPost45.LongTermCapGainPost45.unutilizedCapgainFlag','Y','scheduleLtcgunUtilizedCapGain54B');
	 enableTable('scheduleCGPost45.shortTermCapGainPost45.unutilizedCapgainFlag','Y','scheduleStcgunUtilizedCapGain54');
	 enableTableWithOutCB('scheduleCGPost45.shortTermCapGainPost45.unutilizedCapgainFlag','Y','scheduleStcgunUtilizedCapGain54B');
	 enableNRItables();
	
	if(document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value=='NRI'){
		//A3
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTPaid')[0].readOnly=false;
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTNotPaid')[0].readOnly=false;
		//A4
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.fullConsideration')[0].readOnly=false;
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.deductSec48.aquisitCost')[0].readOnly=false;
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.deductSec48.improveCost')[0].readOnly=false;
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.deductSec48.expOnTrans')[0].readOnly=false;
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.lossSec94of7Or94of8')[0].readOnly=false;
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.deductSec48.aquisitCost')[0].readOnly=false;

		//B4
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.ltcgWithoutBenefit')[0].readOnly=false;
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.exemptionOrDednUs54')[0].readOnly=false;
				
		//B5
		var tab = document.getElementById('stcg10pctTab'); 
		var inputs = tab.getElementsByTagName('INPUT');
		var selects =  tab.getElementsByTagName('SELECT'); 
		for(var i=0;i<inputs.length;i++){
			if(!(inputs[i].classList.contains("readonly"))){
				inputs[i].readOnly=false;
			}
		}
		for(var i=0;i<selects.length;i++){
			if( !(selects[i].classList.contains("readonly"))){
				selects[i].disabled=false;
			}
		}			
		
		//B6
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.saleonSpecAsset')[0].readOnly=false;
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.dednSpecAssetus115')[0].readOnly=false;
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.saleOtherSpecAsset')[0].readOnly=false;
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.dednOtherSpecAssetus115')[0].readOnly=false;
		
		//B4
		
		tab = document.getElementById('scheduleCGltcg4_ded1'); 
		inputs = tab.getElementsByTagName('INPUT');
		selects =  tab.getElementsByTagName('SELECT'); 
		for(var i=0;i<inputs.length;i++){
			if(!(inputs[i].classList.contains("readonly"))){
				inputs[i].readOnly=false;
			}
		}
		for(var i=0;i<selects.length;i++){
			if( !(selects[i].classList.contains("readonly"))){
				selects[i].disabled=false;
			}
		}			
		
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.exemptionOrDednUs54')[0].readOnly=true;
		
	}else{
		//A3
		var nRItaxSTTPaid = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTPaid')[0];
		nRItaxSTTPaid.readOnly=true;
		nRItaxSTTPaid.value = 0;
		
		var nRItaxSTTNotPaid = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTNotPaid')[0];
		nRItaxSTTNotPaid.readOnly=true;
		nRItaxSTTNotPaid.value = 0;
		
		//A4
		var fullConsideration = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.fullConsideration')[0];
		fullConsideration.readOnly=true;
		fullConsideration.value = 0;
		var aquisitCost = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.deductSec48.aquisitCost')[0];
		aquisitCost.readOnly=true;
		aquisitCost.value = 0;
		var improveCost = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.deductSec48.improveCost')[0];
		improveCost.readOnly=true;
		improveCost.value = 0;
		var expOnTrans = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.deductSec48.expOnTrans')[0];
		expOnTrans.readOnly=true;
		expOnTrans.value = 0;
		var lossSec94of7Or94of8 = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.lossSec94of7Or94of8')[0];
		lossSec94of7Or94of8.readOnly=true;
		lossSec94of7Or94of8.value = 0;
		var aquisitCost = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.deductSec48.aquisitCost')[0];
		aquisitCost.readOnly=true;
		aquisitCost.value = 0;

		//B4
		var ltcgWithoutBenefit = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.ltcgWithoutBenefit')[0];
		ltcgWithoutBenefit.readOnly=true;
		ltcgWithoutBenefit.value = 0;
		var exemptionOrDednUs54 = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.exemptionOrDednUs54')[0];
		exemptionOrDednUs54.readOnly=true;
		exemptionOrDednUs54.value = 0;
		
		//B5
		var tab = document.getElementById('stcg10pctTab');
		var inputs = tab.getElementsByTagName('INPUT');
		var selects =  tab.getElementsByTagName('SELECT');
		for(var i=0;i<inputs.length;i++){
			if(!inputs[i].classList.contains("readonly")){
				inputs[i].readOnly=true;
				inputs[i].value = '';
			}
		}
		for(var i=0;i<selects.length;i++){
			if(!selects[i].classList.contains("readonly")){
				selects[i].disabled=true;
				selects[i].selectedIndex=0;
			}
		}			
		
		//B6
		var saleonSpecAsset = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.saleonSpecAsset')[0];
		saleonSpecAsset.readOnly=true;
		saleonSpecAsset.value=0;
		var dednSpecAssetus115 = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.dednSpecAssetus115')[0];
		dednSpecAssetus115.readOnly=true;
		dednSpecAssetus115.value=0;
		var saleOtherSpecAsset = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.saleOtherSpecAsset')[0];
		saleOtherSpecAsset.readOnly=true;
		saleOtherSpecAsset.value=0;
		var dednOtherSpecAssetus115 = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.dednOtherSpecAssetus115')[0];
		dednOtherSpecAssetus115.readOnly=true;
		dednOtherSpecAssetus115.value=0;
		
		//B4
		var tab = document.getElementById('scheduleCGltcg4_ded1');
		var inputs = tab.getElementsByTagName('INPUT');
		var selects =  tab.getElementsByTagName('SELECT');
		
		$("#scheduleCGltcg4_ded1 input").attr("checked" , true);
	    deleteRowTable('scheduleCGltcg4_ded1',1,2);
		$("#scheduleCGltcg4_ded1 input").attr("checked" , false);
		
		for(var i=0;i<inputs.length;i++){
			if(!inputs[i].classList.contains("readonly")){
				inputs[i].readOnly=true;
				inputs[i].value = '';
			}
		}
		for(var i=0;i<selects.length;i++){
			if(!selects[i].classList.contains("readonly")){
				selects[i].disabled=true;
				selects[i].selectedIndex=0;
			}
		}		
	}
}

//To enable Field
function enableField(src,val,targets){ 
	var srcField = document.getElementsByName(src)[0];
	if(contains(val,srcField.value)){
		for(var i=2;i<arguments.length; i++){	
			var targetField = document.getElementsByName(arguments[i])[0];		
				targetField.disabled= false;
				targetField.readOnly=false;
		}
	}else{
		for(var i=2;i<arguments.length; i++){
			var targetField = document.getElementsByName(arguments[i])[0];		
			if(targetField.type=='select-one'){
				targetField.selectedIndex = 0;
			}else{
				targetField.value='';
			}
			targetField.disabled= true;
			targetField.readOnly=true;
		}	
	}
	
}

//To check the given value is there in the array or not
function contains(arr, val){
	if(arr.constructor.name=="Array"){
		for(var i=0;i<arr.length; i++){
			if(arr[i]==val){
				return true;
			}
		}
		return false;
	}else{
		return (arr==val);
	}
}

//To populate name in Verification section
function populateVerName(){
	
	var fName=document.getElementsByName('partAGEN1.personalInfo.assesseeName.firstName')[0].value;
	var mName=document.getElementsByName('partAGEN1.personalInfo.assesseeName.middleName')[0].value;
	var lName=document.getElementsByName('partAGEN1.personalInfo.assesseeName.surNameOrOrgName')[0].value;
	
	var verName;
	
	if(fName !='' && mName!='' ){
	verName=fName+ ' '+ mName +' '+lName ;
	}
	
	else if(fName =='' && mName!='' ){
		verName= mName +' '+lName ;
		}
	
	else if(fName !='' && mName =='' ){
		verName=fName+ ' '+lName ;
		}
	else{
		verName=lName;
	}
	document.getElementsByName('verification.declaration.assesseeVerName')[0].value=verName.toUpperCase();
	
}

//To check schedule FA mandatory
function checkSchFAMandatory() {
    
    	var table1 = checkRowBlank('schFADtlsFrignAssets', 2, 1);
		var table2 = checkRowBlank('schFADtlsFinIntrest', 2, 1);
		var table3 = checkRowBlank('schFADtlsImmvbleProp', 2, 1);
		var table4 = checkRowBlank('schFADtlsOtherAsset', 2, 1);
		var table5 = checkRowBlank('schFADtlsSigningAuth', 2, 1);
		var table6 = checkRowBlank('schFADtlsTrusts', 2, 1);
		var table7 = checkRowBlank('DetailsOthIncomeOutsideIndia', 2, 1);

	if(document.getElementsByName('partBTTI.assetOutIndiaFlag')[0].value=='YES' && document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value!='NRI') {		
		if(table1 && table2 && table3 && table4 && table5 && table6 && table7) {
			j.setFieldError('scheduleFA.detailsForiegnBank[0].countryCode','Please enter any one table in Schedule FA.');
			addErrorXHTML('','Please enter any one table in Schedule FA.');
		}
	}
        if(document.getElementsByName('partBTTI.assetOutIndiaFlag')[0].value=='NO' && document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value!='NRI') {		
		if( !(table1 && table2 && table3 && table4 && table5 && table6 && table7) ) {
			j.setFieldError('partBTTI.assetOutIndiaFlag','Please correct your selection of assets outside India in Part B -TTI.');
			addErrorXHTML('','Please correct your selection of assets outside India in Part B -TTI.');
		}
	}
}

//To calculate total amount of schedule 5A
function totAmtOfSched5A(){
	document.getElementsByName('schedule5A2014.totalHeadIncome.incRecvdUndHead')[0].value=eval(
		parseInt(coalesce(document.getElementsByName('schedule5A2014.hPHeadIncome.incRecvdUndHead')[0].value),10)+
		parseInt(coalesce(document.getElementsByName('schedule5A2014.capGainHeadIncome.incRecvdUndHead')[0].value),10)+
		parseInt(coalesce(document.getElementsByName('schedule5A2014.otherSourcesHeadIncome.incRecvdUndHead')[0].value),10));
	
	document.getElementsByName('schedule5A2014.totalHeadIncome.amtApprndOfSpouse')[0].value=eval(
			parseInt(coalesce(document.getElementsByName('schedule5A2014.hPHeadIncome.amtApprndOfSpouse')[0].value),10)+
			parseInt(coalesce(document.getElementsByName('schedule5A2014.capGainHeadIncome.amtApprndOfSpouse')[0].value),10)+
			parseInt(coalesce(document.getElementsByName('schedule5A2014.otherSourcesHeadIncome.amtApprndOfSpouse')[0].value),10));
	
	document.getElementsByName('schedule5A2014.totalHeadIncome.amtTDSDeducted')[0].value=eval(
			parseInt(coalesce(document.getElementsByName('schedule5A2014.hPHeadIncome.amtTDSDeducted')[0].value),10)+
			parseInt(coalesce(document.getElementsByName('schedule5A2014.capGainHeadIncome.amtTDSDeducted')[0].value),10)+
			parseInt(coalesce(document.getElementsByName('schedule5A2014.otherSourcesHeadIncome.amtTDSDeducted')[0].value),10));
	
	document.getElementsByName('schedule5A2014.totalHeadIncome.tDSApprndOfSpouse')[0].value=eval(
			parseInt(coalesce(document.getElementsByName('schedule5A2014.hPHeadIncome.tDSApprndOfSpouse')[0].value),10)+
			parseInt(coalesce(document.getElementsByName('schedule5A2014.capGainHeadIncome.tDSApprndOfSpouse')[0].value),10)+
			parseInt(coalesce(document.getElementsByName('schedule5A2014.otherSourcesHeadIncome.tDSApprndOfSpouse')[0].value),10));
}

//To disable Schedule 5A
function disableSchedule5A(){

	var tabl = document.getElementById('schedule5A');
	var allInputTags = tabl.getElementsByTagName('input');
	
	var portugeseStatus=document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].value;
	
	for(var i = 0; i < allInputTags.length; i++) {
		if(portugeseStatus=='Y'){
			allInputTags[i].disabled=false;
			allInputTags[i].readOnly=false;		
			document.getElementsByName('schedule5A2014.busHeadIncome.incRecvdUndHead')[0].disabled=true;
			document.getElementsByName('schedule5A2014.busHeadIncome.amtApprndOfSpouse')[0].disabled=true;
			document.getElementsByName('schedule5A2014.busHeadIncome.amtTDSDeducted')[0].disabled=true;
			document.getElementsByName('schedule5A2014.busHeadIncome.tDSApprndOfSpouse')[0].disabled=true;
			
			document.getElementsByName('schedule5A2014.totalHeadIncome.incRecvdUndHead')[0].disabled=true;
			document.getElementsByName('schedule5A2014.totalHeadIncome.amtApprndOfSpouse')[0].disabled=true;
			document.getElementsByName('schedule5A2014.totalHeadIncome.amtTDSDeducted')[0].disabled=true;
			document.getElementsByName('schedule5A2014.totalHeadIncome.tDSApprndOfSpouse')[0].disabled=true;			
			main.enableTabs(19);
                        
		}else{
			allInputTags[i].disabled=true;
			allInputTags[i].readOnly=true;
			allInputTags[i].value="";	
			
	
		}
	}
	document.getElementsByName('schedule5A2014.capGainHeadIncome.incRecvdUndHead')[0].disabled=true;
	document.getElementsByName('schedule5A2014.capGainHeadIncome.amtApprndOfSpouse')[0].disabled=true;
	document.getElementsByName('schedule5A2014.capGainHeadIncome.amtTDSDeducted')[0].disabled=true;
	document.getElementsByName('schedule5A2014.capGainHeadIncome.tDSApprndOfSpouse')[0].disabled=true;

}

//To calculate Total EI values
function calTotalEI(){
	document.getElementsByName('scheduleEI.totalExemptInc')[0].value=
		coalesceSetRet('scheduleEI.interestInc')+
		coalesceSetRet('scheduleEI.dividendInc')+
		coalesceSetRet('scheduleEI.ltcgWhereSTTPaid')+
		coalesceSetRet('scheduleEI.netAgriIncOrOthrIncRule7')+		
		coalesceSetRet('scheduleEI.others');
}

//To calculate Schedule S
function calSchS(tableId){
	try{

		var tab = document.getElementById(tableId);
		var rowcount= tab.rows.length;
		var salaryCount = parseInt(rowcount/14,10);// 14 --> Total number of fields will be added for each click 'Add Salary'
		var sumTotal=0;
		var salaryTotal=0;
		var exemptUs10Total = 0;

	for(var i = 0; i < salaryCount; i++) {

	var salary = document.getElementsByName('scheduleS.salaries['+i+'].salarys.salary')[0]; salary.value = coalesce(salary.value);
	var allowancesNotExempt = document.getElementsByName('scheduleS.salaries['+i+'].salarys.allowancesNotExempt')[0]; allowancesNotExempt.value = coalesce(allowancesNotExempt.value);
    var travelConcession = document.getElementsByName('scheduleS.salaries['+i+'].salarys.travelConcession')[0]; travelConcession.value = coalesce(travelConcession.value);
    var taxPaidNonMonetary = document.getElementsByName('scheduleS.salaries['+i+'].salarys.TaxPaidNonMonetary')[0]; taxPaidNonMonetary.value = coalesce(taxPaidNonMonetary.value);
    var allowanceExpHouseRent = document.getElementsByName('scheduleS.salaries['+i+'].salarys.allowanceExpHouseRent')[0]; allowanceExpHouseRent.value = coalesce(allowanceExpHouseRent.value);
    var otherAllowances = document.getElementsByName('scheduleS.salaries['+i+'].salarys.otherAllowances')[0]; otherAllowances.value = coalesce(otherAllowances.value);
	var valueOfPerquisites = document.getElementsByName('scheduleS.salaries['+i+'].salarys.valueOfPerquisites')[0]; valueOfPerquisites.value = coalesce(valueOfPerquisites.value);
	var profitsInLieuOfSalary = document.getElementsByName('scheduleS.salaries['+i+'].salarys.profitsinLieuOfSalary')[0]; profitsInLieuOfSalary.value = coalesce(profitsInLieuOfSalary.value);
	var deductionUS16 = document.getElementsByName('scheduleS.salaries['+i+'].salarys.deductionUnderSection16')[0]; deductionUS16.value = coalesce(deductionUS16.value);
	var incomeChargeable = document.getElementsByName('scheduleS.salaries['+i+'].salarys.incomeFromSalary')[0]; incomeChargeable.value = coalesce(incomeChargeable.value);
	
	salaryTotal = eval(parseInt( coalesce(salary.value) ,10) + parseInt( coalesce(allowancesNotExempt.value) ,10)
			+ parseInt( coalesce(valueOfPerquisites.value) ,10) + parseInt( coalesce(profitsInLieuOfSalary.value) ,10));
			
	 if((parseInt(salaryTotal,0) < parseInt( coalesce(deductionUS16.value)  ,10)) || parseInt( coalesce(deductionUS16.value),10) > 7500) {
				addErrorXHTML(document.getElementsByName('scheduleS.salaries['+i+'].salarys.deductionUnderSection16')[0],'Deduction u/s 16 should not exceed ' + Math.min(7500,salaryTotal),true);
				document.getElementsByName('scheduleS.salaries['+i+'].salarys.deductionUnderSection16')[0].value="0";
		}
		
	incomeChargeable.value=eval(parseInt(salary.value,10)+parseInt(valueOfPerquisites.value,10)+parseInt(profitsInLieuOfSalary.value,10)+parseInt(allowancesNotExempt.value,10)-parseInt(deductionUS16.value,10));

	if(incomeChargeable.value<0){
		incomeChargeable.value=parseInt('0',10);
	}
	sumTotal = eval(parseInt(sumTotal,10) + parseInt(coalesce(document.getElementsByName('scheduleS.salaries['+i+'].salarys.incomeFromSalary')[0].value),10));
	exemptUs10Total = eval(parseInt(travelConcession.value,10)+parseInt(taxPaidNonMonetary.value,10)+parseInt(allowanceExpHouseRent.value,10)+parseInt(otherAllowances.value,10));
	document.getElementsByName('scheduleS.incomeChargeable')[0].value  = parseInt(sumTotal,10);
	document.getElementsByName('scheduleS.salaries['+i+'].salarys.allowancesExemptUSection10')[0].value = parseInt(exemptUs10Total,10);
    }


	}catch(e){
	alert('Exception in calSchS method: ' +e);
	}
}

//To add Schedule Salary
function addScheduleSalary(){
	var mainTable=document.getElementById('scheduleSalaryMain').rows;
	var tobeInsertBefore=document.getElementById('scheduleSalaryAddRow');
	var flag=false;
	var totRow=Math.floor(mainTable.length / 14) + 1;// 14 --> Total number of fields will be added for each click 'Add Salary'
	var iterate=eval(parseInt(totRow)-1);
	for(var i=0;i<mainTable.length;i++){
	var cloneNode=mainTable[i].cloneNode(true);
		if(mainTable[i].id =='scheduleSalary1st'){
		flag=true;
		cloneNode.cells[0].innerHTML=totRow;
		}

	if(flag ){
		
		var cellsTot=cloneNode.cells;
		for(var j=0;j<cellsTot.length;j++){
			cloneNode.cells[j].innerHTML=cloneNode.cells[j].
			
			
			innerHTML.replace('1a',totRow+'a').replace('1b',totRow+'b').replace('1c',totRow+'c').replace('1d',totRow+'d').replace('1e',totRow+'e').replace('1f',totRow+'f').replace('1g',totRow+'g').replace('1h',totRow+'h').replace('1i',totRow+'i').replace('property 1','property '+totRow).replace('property 1','property '+totRow);
		}
		
		var inputTags=cloneNode.getElementsByTagName('input');
		for(var a=0;a<inputTags.length;a++){
			inputTags[a].name=inputTags[a].name.replace('[0]','['+iterate+']');
		   inputTags[a].id=inputTags[a].name.replace(/([\.\[\]])/g,'_').replace(/(__)/g,'_');
		  
		   var blurAttr=inputTags[a].getAttribute('onblur');
			if(blurAttr!=null){
				blurAttr=blurAttr+";";
			}else{
				blurAttr="";
			}
			inputTags[a].setAttribute('onblur',blurAttr+'j.blur(this,this.name,this.value);');
		}
		
		var selectTags=cloneNode.getElementsByTagName('select');
		for(var a=0;a<selectTags.length;a++){
			selectTags[a].name=selectTags[a].name.replace('[0]','['+iterate+']');
			selectTags[a].value='';
						selectTags[a].id=selectTags[a].name.replace(/([\.\[\]])/g,'_').replace(/(__)/g,'_');
						
						var blurAttr=selectTags[a].getAttribute('onblur');
						if(blurAttr!=null){
							blurAttr=blurAttr+";";
						}else{
							blurAttr="";
						}
						selectTags[a].setAttribute('onblur',blurAttr+'j.blur(this,this.name,this.value);');
		}
		
		var textareaTags=cloneNode.getElementsByTagName('textarea');
		for(var a=0;a<textareaTags.length;a++){
			textareaTags[a].name=textareaTags[a].name.replace('[0]','['+iterate+']');
			textareaTags[a].value='';
						textareaTags[a].id=textareaTags[a].name.replace(/([\.\[\]])/g,'_').replace(/(__)/g,'_');
						
						var blurAttr=textareaTags[a].getAttribute('onblur');
						if(blurAttr!=null){
							blurAttr=blurAttr+";";
						}else{
							blurAttr="";
						}
						textareaTags[a].setAttribute('onblur',blurAttr+'j.blur(this,this.name,this.value);');
		}
		
		document.getElementById('scheduleSalaryMain').getElementsByTagName('tr')[0].parentNode.insertBefore(cloneNode,tobeInsertBefore);
		}
	if(mainTable[i].id =='scheduleSalaryEnd'){
		flag=false;
		break;
		}
	}

	var newVal = eval( parseInt(totRow) + 1);
		document.getElementById('scheduleSlast').cells[0].innerHTML=newVal;

	if($('#scheduleSalaryAddRow')[0].parentNode.children.length==11){
		$('#delSalaryButtonId').prop('disabled', true);
	}else if($('#scheduleSalaryAddRow')[0].parentNode.children.length>11){
		$('#delSalaryButtonId').prop('disabled', false);
	}
	
	var table=document.getElementById('scheduleSalaryMain');
	modifyRow(table);
	checkMaxLengthLimit();
	}

//To delete Schedule Salary 
function delScheduleSalaryForItr2(){

	if($('#scheduleSalaryAddRow')[0].parentNode.children.length>16){

		for(var i=0;i<14;i++){
		
			$('#scheduleSalaryAddRow')[0].parentNode.deleteRow($('#scheduleSalaryAddRow')[0].parentNode.children.length-3);
		}
		
	}
	var totRow=document.getElementById('scheduleSlast').cells[0].textContent;
	var newVal = eval( parseInt(totRow)-1);
		var newText='Total (';
		for(var k=1;k<newVal;k++){
			newText=newText+k+'i +';
		}
		newText=newText+newVal+'a +'+newVal+'b )';
		document.getElementById('scheduleSlast').cells[0].innerHTML=newVal;


	if($('#scheduleSalaryAddRow')[0].parentNode.children.length==16){
		$('#delSalaryButtonId').prop('disabled', true);
	}else if($('#scheduleSalaryAddRow')[0].parentNode.children.length>16){
		$('#delSalaryButtonId').prop('disabled', false);
	}		
	calcITR2();
	}

//To calculate schedule CYLA
function calculateCYLA(cgosIncome){
	try{
		//prefill the CYLA-schedule
		prefillCYLA();
		setOffOthSrcLossCYLA(cgosIncome);
				
		// Current year's Income remaining after set off
		document.getElementsByName('scheduleCYLA.Salaries.incCYLA.incOfCurYrAfterSetOff')[0].value =
			coalescePath('scheduleCYLA.Salaries.incCYLA.incOfCurYrUnderThatHead') -
			coalescePath('scheduleCYLA.Salaries.incCYLA.hPlossCurYrSetoff')-
			coalescePath('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff');
		if(coalescePath('scheduleCYLA.Salaries.incCYLA.incOfCurYrAfterSetOff')<0){
			addErrorXHTML(document.getElementsByName('scheduleCYLA.Salaries.incCYLA.incOfCurYrAfterSetOff')[0],
				'This figure cannot be negative. Please rearrange your figures',true);
			j.setFieldError('scheduleCYLA.Salaries.incCYLA.incOfCurYrAfterSetOff',
				'This figure cannot be negative. Please rearrange your figures');
			
		}
		
		// Current year's Income remaining after set off
		document.getElementsByName('scheduleCYLA.houseProperty.incCYLA.incOfCurYrAfterSetOff')[0].value =
			coalescePath('scheduleCYLA.houseProperty.incCYLA.incOfCurYrUnderThatHead') -
			coalescePath('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff');
		if(coalescePath('scheduleCYLA.houseProperty.incCYLA.incOfCurYrAfterSetOff')<0){
			addErrorXHTML(document.getElementsByName('scheduleCYLA.houseProperty.incCYLA.incOfCurYrAfterSetOff')[0],
				'This figure cannot be negative. Please rearrange your figures',true);
			j.setFieldError('scheduleCYLA.houseProperty.incCYLA.incOfCurYrAfterSetOff',
				'This figure cannot be negative. Please rearrange your figures');
			
		}
		// 	Other sources
		document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.incOfCurYrAfterSetOff')[0].value=
			coalescePath('scheduleCYLA.othSrcInclRaceHorse.incCYLA.incOfCurYrUnderThatHead')-
			coalescePath('scheduleCYLA.othSrcInclRaceHorse.incCYLA.hPlossCurYrSetoff');
		if(coalescePath('scheduleCYLA.othSrcInclRaceHorse.incCYLA.incOfCurYrAfterSetOff')<0){
			addErrorXHTML(document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.incOfCurYrAfterSetOff')[0],
				'This figure cannot be negative. Please rearrange your figures',true);
			j.setFieldError('scheduleCYLA.othSrcInclRaceHorse.incCYLA.incOfCurYrAfterSetOff',
				'This figure cannot be negative. Please rearrange your figures');
		}
		// Profit from owning and maintaining race horses
		document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrAfterSetOff')[0].value=
			coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrUnderThatHead')-
			coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.hPlossCurYrSetoff')-
			coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.othSrcLossNoRaceHorseSetoff');
		if(coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrAfterSetOff')<0){
			addErrorXHTML(document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrAfterSetOff')[0],
				'This figure cannot be negative. Please rearrange your figures',true);
			j.setFieldError('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrAfterSetOff',
				'This figure cannot be negative. Please rearrange your figures');
		}

		//total loss setoff
		document.getElementsByName('scheduleCYLA.totalLossSetOff.totHPlossCurYrSetoff')[0].value=
			coalescePath('scheduleCYLA.Salaries.incCYLA.hPlossCurYrSetoff')+			
			coalescePath('scheduleCYLA.othSrcInclRaceHorse.incCYLA.hPlossCurYrSetoff')+
			coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.hPlossCurYrSetoff');

		document.getElementsByName('scheduleCYLA.totalLossSetOff.totOthSrcLossNoRaceHorseSetoff')[0].value=
			coalescePath('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff')+
			coalescePath('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff')+
			coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.othSrcLossNoRaceHorseSetoff');
			
		//Loss remaining after set-off
		document.getElementsByName('scheduleCYLA.lossRemAftSetOff.balHPlossCurYrAftSetoff')[0].value=
			coalescePath('scheduleCYLA.totalCurYr.totHPlossCurYr')-coalescePath('scheduleCYLA.totalLossSetOff.totHPlossCurYrSetoff');
		if(coalescePath('scheduleCYLA.lossRemAftSetOff.balHPlossCurYrAftSetoff')<0){
			addErrorXHTML(document.getElementsByName('scheduleCYLA.lossRemAftSetOff.balHPlossCurYrAftSetoff')[0],
				'This figure cannot be negative. Please rearrange your figures',true);
			j.setFieldError('scheduleCYLA.lossRemAftSetOff.balHPlossCurYrAftSetoff',
				'This figure cannot be negative. Please rearrange your figures');
		}

		document.getElementsByName('scheduleCYLA.lossRemAftSetOff.balOthSrcLossNoRaceHorseAftSetoff')[0].value=
			coalescePath('scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse')-coalescePath('scheduleCYLA.totalLossSetOff.totOthSrcLossNoRaceHorseSetoff');
		if(coalescePath('scheduleCYLA.lossRemAftSetOff.balOthSrcLossNoRaceHorseAftSetoff')<0){
			addErrorXHTML(document.getElementsByName('scheduleCYLA.lossRemAftSetOff.balOthSrcLossNoRaceHorseAftSetoff')[0],
				'This figure cannot be negative. Please rearrange your figures',true);
			j.setFieldError('scheduleCYLA.lossRemAftSetOff.balOthSrcLossNoRaceHorseAftSetoff',
				'This figure cannot be negative. Please rearrange your figures');
			
		}
					
			var losses = coalescePath('scheduleCYLA.lossRemAftSetOff.balHPlossCurYrAftSetoff')+
			   coalescePath('scheduleCYLA.lossRemAftSetOff.balOthSrcLossNoRaceHorseAftSetoff');
			
			if( losses> 0){
				var incomeRem =
					coalescePath('scheduleCYLA.Salaries.incCYLA.incOfCurYrAfterSetOff')+
					coalescePath('scheduleCYLA.houseProperty.incCYLA.incOfCurYrAfterSetOff')+					
					coalescePath('scheduleCYLA.othSrcInclRaceHorse.incCYLA.incOfCurYrAfterSetOff')+
					coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrAfterSetOff');
				
				if(incomeRem > 0 ){
					addErrorXHTML('', 'Losses of the current year should be first setoff with the income of the current year in schedule CYLA.',true);
					
					if(coalescePath('scheduleCYLA.lossRemAftSetOff.balHPlossCurYrAftSetoff')>0){
						j.setFieldError('scheduleCYLA.lossRemAftSetOff.balHPlossCurYrAftSetoff', 
							'Losses of the current year should be first setoff with the income of the current year in schedule CYLA.');
					}else if(coalescePath('scheduleCYLA.lossRemAftSetOff.balOthSrcLossNoRaceHorseAftSetoff')>0){
						j.setFieldError('scheduleCYLA.lossRemAftSetOff.balOthSrcLossNoRaceHorseAftSetoff', 
							'Losses of the current year should be first setoff with the income of the current year in schedule CYLA.');
					}
				}
			}		
		
		calcBFLA(cgosIncome);

	}catch(e){
		alert('Exception in calcCYLA method=' + e.stack);
	}
}

//To prefill scheudule CYLA
function prefillCYLA(){
	try{
		
		//prefilling column :: Income of current year Salaries  (Fill this column only if income is zero or positive) - House Property
		//Field 7 of Sch s , only if field 7 is positive
		document.getElementsByName('scheduleCYLA.Salaries.incCYLA.incOfCurYrUnderThatHead')[0].value =
			zeroOrMore(coalescePath('scheduleS.incomeChargeable'));
		
		//Field 3c of Schedule HP) , only if 3c is positive
		document.getElementsByName('scheduleCYLA.houseProperty.incCYLA.incOfCurYrUnderThatHead')[0].value =
			zeroOrMore(coalescePath('scheduleHP.totalIncomeChargeableUnHP'));
					
		//prefilling column :: Other sources income
		//Field (1i of schedule OS)
		document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.incOfCurYrUnderThatHead')[0].value =
			zeroOrMore(coalescePath('scheduleOS.balanceNoRaceHorse'));
		
		//prefilling column :: Profit from owning and maintaining race horses
		//Field (3c of schedule OS)
		document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrUnderThatHead')[0].value =
			zeroOrMore(coalescePath('scheduleOS.incFromOwnHorse.balanceOwnRaceHorse'));
		
		// populating losses in the respective heads
		coalescePath('scheduleCYLA.totalCurYr.totHPlossCurYr');
		if(!isPostv('scheduleHP.totalIncomeChargeableUnHP')){
			document.getElementsByName('scheduleCYLA.totalCurYr.totHPlossCurYr')[0].value =
				Math.abs(coalescePath('scheduleHP.totalIncomeChargeableUnHP'));
		}else{
			document.getElementsByName('scheduleCYLA.totalCurYr.totHPlossCurYr')[0].value = 0;
		}

		coalescePath('scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse');
		if(!isPostv('scheduleOS.balanceNoRaceHorse')){			
			document.getElementsByName('scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse')[0].value = 
				Math.abs(coalescePath('scheduleOS.balanceNoRaceHorse')) ;
		}else{
			document.getElementsByName('scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse')[0].value = 0;
		}

	}catch(e){
		alert('Exception in prefillCYLA() method =' + e.stack);
	}
}

//To setOff Other Source Loss CYLA
function setOffOthSrcLossCYLA(cgosIncome){
	try{
		
		document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.othSrcLossNoRaceHorseSetoff')[0].value = 0;
				
			document.getElementsByName('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff')[0].value = 0;			
				
			document.getElementsByName('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff')[0].value = 0;			
	
			
		
		var setOffRem = coalescePath('scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse')-
			coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrUnderThatHead');
			
		// 1. Race Horse
		if(parseInt(setOffRem,10)>=0){
			document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.othSrcLossNoRaceHorseSetoff')[0].value =
					coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrUnderThatHead');
			
		}else{
			document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.othSrcLossNoRaceHorseSetoff')[0].value =
				coalescePath('scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse');
			setOffRem =0 ;
		}
		
		//2.salary
		var prevSetOffRem = setOffRem;
		setOffRem = parseInt(setOffRem,10) - coalescePath('scheduleCYLA.Salaries.incCYLA.incOfCurYrUnderThatHead');
		
		if(parseInt(setOffRem,10)>=0){
			if( !checkIfChanged('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff')){				
				document.getElementsByName('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff')[0].value =
					coalescePath('scheduleCYLA.Salaries.incCYLA.incOfCurYrUnderThatHead');				
			}else{
				checkFirstLessThanMinOthTwo('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff',
						'scheduleCYLA.Salaries.incCYLA.incOfCurYrUnderThatHead','scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse',
						coalescePath('scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse')-
						coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.othSrcLossNoRaceHorseSetoff'));
				
				setOffRem = parseInt(prevSetOffRem,10) - coalescePath('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff');
			}
		}else{
			if( !checkIfChanged('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff')){				
				document.getElementsByName('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff')[0].value = prevSetOffRem;
			}else{
				checkFirstLessThanMinOthTwo('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff',
						'scheduleCYLA.Salaries.incCYLA.incOfCurYrUnderThatHead','scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse',
						coalescePath('scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse')-
						coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.othSrcLossNoRaceHorseSetoff'));
			}		
			setOffRem =0 ;
		}
		
		//3.House property
		prevSetOffRem = setOffRem;
		setOffRem = parseInt(setOffRem,10) - coalescePath('scheduleCYLA.houseProperty.incCYLA.incOfCurYrUnderThatHead');
		if(parseInt(setOffRem,10)>=0){		
			if( !checkIfChanged('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff')){				
				document.getElementsByName('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff')[0].value =
					coalescePath('scheduleCYLA.houseProperty.incCYLA.incOfCurYrUnderThatHead');				
			}else{
				checkFirstLessThanMinOthTwo('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff',
					'scheduleCYLA.houseProperty.incCYLA.incOfCurYrUnderThatHead','scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse',
					coalescePath('scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse')-
					coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.othSrcLossNoRaceHorseSetoff')-
					coalescePath('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff'));
				
				setOffRem = parseInt(prevSetOffRem,10) - coalescePath('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff');
			}
		}else{
		
			if( !checkIfChanged('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff')){				
				document.getElementsByName('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff')[0].value = prevSetOffRem;				
			}else{				
				checkFirstLessThanMinOthTwo('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff',
					'scheduleCYLA.houseProperty.incCYLA.incOfCurYrUnderThatHead','scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse',
					coalescePath('scheduleCYLA.totalCurYr.totOthSrcLossNoRaceHorse')-
					coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.othSrcLossNoRaceHorseSetoff')-
					coalescePath('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff'));
			}			
			setOffRem =0 ;
		}
		
		//4. Short-term capital gain taxable @ 30% 
		prevSetOffRem = setOffRem;
		if(parseInt(setOffRem,10)>=0){
			
		}else{
		
				
			setOffRem =0;
		}
		
		//5.Short-term capital gain taxable at applicable rates
		prevSetOffRem = setOffRem;
		setOffRem = parseInt(setOffRem,10);
		if(parseInt(setOffRem,10)>=0){		
			
		}else{
		
					
			setOffRem =0 ;
		}
		
		// 6)Long term capital gain taxable @ 20%
		prevSetOffRem = setOffRem;
		
		//7.Short-term capital gain taxable @ 15%
		prevSetOffRem = setOffRem;
		
		// 8)Long term capital gain taxable @ 10%
		prevSetOffRem = setOffRem;		
		
		setOffHPLossCYLA(cgosIncome);
	}catch(e){
		alert('Exception in setOffOthSrcLossCYLA() method =' + e.stack);
	}
}

//To setOff HP Loss CYLA
function setOffHPLossCYLA(cgosIncome){
	try{
		
		document.getElementsByName('scheduleCYLA.Salaries.incCYLA.hPlossCurYrSetoff')[0].value = 0;
		
		document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.hPlossCurYrSetoff')[0].value = 0;
		
		document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.hPlossCurYrSetoff')[0].value = 0;
		

		// 1. salary Income	
		var salarySetOffRem = zeroOrMore(coalescePath('scheduleCYLA.Salaries.incCYLA.incOfCurYrUnderThatHead')-
					coalescePath('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff'));
		var prevSetOffRem = coalescePath('scheduleCYLA.totalCurYr.totHPlossCurYr');
		var setOffRem = prevSetOffRem - salarySetOffRem;
		
		if(setOffRem>=0){
			if(coalescePath('scheduleCYLA.totalCurYr.totHPlossCurYr')==0){
				document.getElementsByName('scheduleCYLA.Salaries.incCYLA.hPlossCurYrSetoff')[0].value = 0;
			}else{
			
					document.getElementsByName('scheduleCYLA.Salaries.incCYLA.hPlossCurYrSetoff')[0].value = salarySetOffRem;					
				
			}
		}else{
				document.getElementsByName('scheduleCYLA.Salaries.incCYLA.hPlossCurYrSetoff')[0].value =
					coalescePath('scheduleCYLA.totalCurYr.totHPlossCurYr');				
			
			setOffRem =0 ;
		}
		
		//2) Other sources (excluding profit from owning race horses)
		
		prevSetOffRem = setOffRem;		
		setOffRem = setOffRem - coalescePath('scheduleCYLA.othSrcInclRaceHorse.incCYLA.incOfCurYrUnderThatHead');
		if(setOffRem>=0){		
			if(prevSetOffRem==0){		
				document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.hPlossCurYrSetoff')[0].value = 0;
			}else{
					document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.hPlossCurYrSetoff')[0].value =
						coalescePath('scheduleCYLA.othSrcInclRaceHorse.incCYLA.incOfCurYrUnderThatHead');					
				
			}
		}else{			
				document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.hPlossCurYrSetoff')[0].value = prevSetOffRem;			
			
			setOffRem =0 ;
		}
				
		//3) Profit from owning and maintaining race horse
		var raceHrsSetOffRem = zeroOrMore(coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrUnderThatHead')-
			coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.othSrcLossNoRaceHorseSetoff'));
		
		prevSetOffRem = setOffRem;
		setOffRem = setOffRem - raceHrsSetOffRem;
		if(setOffRem>=0){
			if(prevSetOffRem==0){
				document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.hPlossCurYrSetoff')[0].value = 0;
			}else{				
					document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.hPlossCurYrSetoff')[0].value = raceHrsSetOffRem;					
				
			}
		}else{
				document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.hPlossCurYrSetoff')[0].value = prevSetOffRem;				
			
			setOffRem =0 ;
		}

	}catch(e){
		alert('Exception in setOffHPLossCYLA method= ' + e.stack);
	}
}

function setFirstToSecondMax(first,second,target){
	try{
		if(coalescePath(first) > coalescePath(second)){
			document.getElementsByName(target)[0].value= coalescePath(second);
		}else{
			document.getElementsByName(target)[0].value= coalescePath(first);
		}
	}catch(e){
		alert('Exception in setFirstToSecondMax method= '+e.stack );
	}
}

//To calculate BFLA
function calcBFLA(cgosIncome){
try{
	prefillBFLA();
	calcCFL_sumAll();
	
	setFirstToSecondMax('scheduleCFL.totalOfBFLossesEarlierYrs.lossSummaryDetail.hpLossCF',
				'scheduleBFLA.hp.incBFLA.incOfCurYrUndHeadFromCYLA',
				'scheduleBFLA.hp.incBFLA.bFlossPrevYrUndSameHeadSetoff');
	
		
		setFirstToSecondMax('scheduleCFL.totalOfBFLossesEarlierYrs.lossSummaryDetail.othSrcLossRaceHorseCF',
						'scheduleBFLA.profitFrmRaceHorse.incBFLA.incOfCurYrUndHeadFromCYLA',
						'scheduleBFLA.profitFrmRaceHorse.incBFLA.bFlossPrevYrUndSameHeadSetoff');
		
						
		//calculating the income after setOff
			
			document.getElementsByName('scheduleBFLA.hp.incBFLA.incOfCurYrAfterSetOffBFLosses')[0].value =
				coalescePath('scheduleBFLA.hp.incBFLA.incOfCurYrUndHeadFromCYLA')-
				coalescePath('scheduleBFLA.hp.incBFLA.bFlossPrevYrUndSameHeadSetoff');		
			
		document.getElementsByName('scheduleBFLA.othSrcInclRaceHorse.incBFLA.incOfCurYrAfterSetOffBFLosses')[0].value =
				coalescePath('scheduleBFLA.othSrcInclRaceHorse.incBFLA.incOfCurYrUndHeadFromCYLA');
			document.getElementsByName('scheduleBFLA.profitFrmRaceHorse.incBFLA.incOfCurYrAfterSetOffBFLosses')[0].value =
				coalescePath('scheduleBFLA.profitFrmRaceHorse.incBFLA.incOfCurYrUndHeadFromCYLA')-
				coalescePath('scheduleBFLA.profitFrmRaceHorse.incBFLA.bFlossPrevYrUndSameHeadSetoff');

		
		// Total of brought forward loss set off			
		document.getElementsByName('scheduleBFLA.totalBFLossSetOff.totBFLossSetoff')[0].value =
				coalescePath('scheduleBFLA.hp.incBFLA.bFlossPrevYrUndSameHeadSetoff')+				
				coalescePath('scheduleBFLA.profitFrmRaceHorse.incBFLA.bFlossPrevYrUndSameHeadSetoff');

			//x :: sum of Current years income remaining after set off 
			document.getElementsByName('scheduleBFLA.incomeOfCurrYrAftCYLABFLA')[0].value =
				coalescePath('scheduleBFLA.salary.incBFLA.incOfCurYrAfterSetOffBFLosses')+
				coalescePath('scheduleBFLA.hp.incBFLA.incOfCurYrAfterSetOffBFLosses')+
				coalescePath('scheduleBFLA.othSrcInclRaceHorse.incBFLA.incOfCurYrAfterSetOffBFLosses')+
				coalescePath('scheduleBFLA.profitFrmRaceHorse.incBFLA.incOfCurYrAfterSetOffBFLosses');
		
			calcCFL(cgosIncome);
		
				
}catch(e){
		alert('Exception in calcBFLA method :' + e.stack);
	}

}

function setOffInOrder(tempLtcgCFL, templtcgBreakUp){
	
	if(tempLtcgCFL>templtcgBreakUp){
			tempLtcgCFL = tempLtcgCFL - templtcgBreakUp;
			templtcgBreakUp =0;
		}else{
			templtcgBreakUp = zeroOrMore(templtcgBreakUp - tempLtcgCFL);
			tempLtcgCFL=0;
		}
}

//To prefill schedule BFLA
function prefillBFLA(){
	try{
	
			
		document.getElementsByName('scheduleBFLA.salary.incBFLA.incOfCurYrUndHeadFromCYLA')[0].value = coalescePath('scheduleCYLA.Salaries.incCYLA.incOfCurYrAfterSetOff');//4ii of CYLA --> 1i of BFLA
		document.getElementsByName('scheduleBFLA.salary.incBFLA.incOfCurYrAfterSetOffBFLosses')[0].value = coalescePath('scheduleCYLA.Salaries.incCYLA.incOfCurYrAfterSetOff');//4ii of CYLA --> 1iii of BFLA
		document.getElementsByName('scheduleBFLA.hp.incBFLA.incOfCurYrUndHeadFromCYLA')[0].value = coalescePath('scheduleCYLA.houseProperty.incCYLA.incOfCurYrAfterSetOff');//4iii of CYLA --> 2i of BFLA
		document.getElementsByName('scheduleBFLA.othSrcInclRaceHorse.incBFLA.incOfCurYrUndHeadFromCYLA')[0].value =  coalescePath('scheduleCYLA.othSrcInclRaceHorse.incCYLA.incOfCurYrAfterSetOff');
		document.getElementsByName('scheduleBFLA.profitFrmRaceHorse.incBFLA.incOfCurYrUndHeadFromCYLA')[0].value =  coalescePath('scheduleCYLA.profitFrmRaceHorse.incCYLA.incOfCurYrAfterSetOff');


	}catch(e){
		alert('Exception in prefillBFLA method' + e.stack);
	}
}

function checkIfChanged(pathToCheck){
	if( (document.getElementsByName(pathToCheck)[0].fieldChanged == undefined) ||
			(document.getElementsByName(pathToCheck)[0].fieldChanged != undefined &&
			 document.getElementsByName(pathToCheck)[0].fieldChanged =='false')){
		return false;
	}else{
		return true;
	}
}

function checkFirstLessThanMinOthTwo(path1, path2, path3,verticalCeiling){
	if(coalesceSetRet(path2) <= verticalCeiling){
		if(coalesceSetRet(path1) > coalesceSetRet(path2)){
			addErrorXHTML(document.getElementsByName(path1)[0] , 'This value cannot be greater than '+ coalesceSetRet(path2),true );
			document.getElementsByName(path1)[0].value = coalesceSetRet(path2);
		}
	}else if(verticalCeiling < coalesceSetRet(path2)){
		if(coalesceSetRet(path1) > verticalCeiling){
			addErrorXHTML(document.getElementsByName(path1)[0] , 'This value cannot be greater than '+ verticalCeiling,true );
			document.getElementsByName(path1)[0].value = verticalCeiling;
		}
	}
}

function checkHPeditableValidity(path1,path2,path4,path3,verticalCeilingHP){
	var tempVal =coalesceSetRet(path2)- coalesceSetRet(path4);	
	if(tempVal <= verticalCeilingHP){
		if(coalesceSetRet(path1) > tempVal){			
			addErrorXHTML(document.getElementsByName(path1)[0] , 'This value cannot be greater than '+tempVal,true );
			document.getElementsByName(path1)[0].value = tempVal;
		}
	}else if(verticalCeilingHP < tempVal){
		if(coalesceSetRet(path1) > verticalCeilingHP){			
			addErrorXHTML(document.getElementsByName(path1)[0] , 'This value cannot be greater than '+ verticalCeilingHP,true );
			document.getElementsByName(path1)[0].value = verticalCeilingHP;
		}
	}
}

//To calculate schedule CFL 
function calcCFL(cgosIncome){
	try{
		
		// adjustment of above losses in schedule BFLA
		document.getElementsByName('scheduleCFL.adjTotBFLossInBFLA.lossSummaryDetail.hpLossCF')[0].value = zeroOrMore(document.getElementsByName('scheduleBFLA.hp.incBFLA.bFlossPrevYrUndSameHeadSetoff')[0].value);
				
		document.getElementsByName('scheduleCFL.adjTotBFLossInBFLA.lossSummaryDetail.othSrcLossRaceHorseCF')[0].value = zeroOrMore(document.getElementsByName('scheduleBFLA.profitFrmRaceHorse.incBFLA.bFlossPrevYrUndSameHeadSetoff')[0].value);
		
		// scheduleCFL.adjTotBFLossInBFLA.lossSummaryDetail.hpLossCF
		document.getElementsByName('scheduleCFL.currentAYloss.lossSummaryDetail.hpLossCF')[0].value =
				Math.abs(coalescePath('scheduleCYLA.lossRemAftSetOff.balHPlossCurYrAftSetoff'));

		// os ----- Enter current year OS if any from 4c of Sch OS. ie. any negative figure.
		document.getElementsByName('scheduleCFL.currentAYloss.lossSummaryDetail.othSrcLossRaceHorseCF')[0].value = parseInt(0,10);
		if(coalescePath('scheduleOS.incFromOwnHorse.balanceOwnRaceHorse') < 0){
			document.getElementsByName('scheduleCFL.currentAYloss.lossSummaryDetail.othSrcLossRaceHorseCF')[0].value =
				Math.abs(coalescePath('scheduleOS.incFromOwnHorse.balanceOwnRaceHorse'));
		}

		
		var firstHp = document.getElementsByName('scheduleCFL.lossCFFromPrev8ThYearFromAY.carryFwdLossDetail.hpLossCF')[0].value;
		var firstOth = document.getElementsByName('scheduleCFL.lossCFFromPrev4ThYearFromAY.carryFwdLossDetail.othSrcLossRaceHorseCF')[0].value;
		
		var adjstHp = document.getElementsByName('scheduleCFL.adjTotBFLossInBFLA.lossSummaryDetail.hpLossCF')[0].value;
		var adjstOth = document.getElementsByName('scheduleCFL.adjTotBFLossInBFLA.lossSummaryDetail.othSrcLossRaceHorseCF')[0].value;
		
		
		if(parseInt(firstHp, 10)>parseInt(adjstHp, 10)){
		document.getElementsByName('scheduleCFL.totalLossCFSummary.lossSummaryDetail.hpLossCF')[0].value =
			zeroOrMore(coalescePath('scheduleCFL.totalOfBFLossesEarlierYrs.lossSummaryDetail.hpLossCF') - firstHp +
			coalescePath('scheduleCFL.currentAYloss.lossSummaryDetail.hpLossCF'));
		}else{
		document.getElementsByName('scheduleCFL.totalLossCFSummary.lossSummaryDetail.hpLossCF')[0].value =
			zeroOrMore(coalescePath('scheduleCFL.totalOfBFLossesEarlierYrs.lossSummaryDetail.hpLossCF') - adjstHp +
			coalescePath('scheduleCFL.currentAYloss.lossSummaryDetail.hpLossCF'));			
		}				
		
		if(parseInt(firstOth, 10)>parseInt(adjstOth, 10)){
		document.getElementsByName('scheduleCFL.totalLossCFSummary.lossSummaryDetail.othSrcLossRaceHorseCF')[0].value =
			zeroOrMore(coalescePath('scheduleCFL.totalOfBFLossesEarlierYrs.lossSummaryDetail.othSrcLossRaceHorseCF')-firstOth+
			coalescePath('scheduleCFL.currentAYloss.lossSummaryDetail.othSrcLossRaceHorseCF'));

		}else{
		document.getElementsByName('scheduleCFL.totalLossCFSummary.lossSummaryDetail.othSrcLossRaceHorseCF')[0].value =
			zeroOrMore(coalescePath('scheduleCFL.totalOfBFLossesEarlierYrs.lossSummaryDetail.othSrcLossRaceHorseCF')-adjstOth+
			coalescePath('scheduleCFL.currentAYloss.lossSummaryDetail.othSrcLossRaceHorseCF'));		

		}

	}catch(e){
		alert('error in calcCFL()= '+e.stack);
	}
}

//To clear all values in CYLA
function clearCYLA(){

	if(document.getElementsByName('scheduleCYLA.Salaries.incCYLA.hPlossCurYrSetoff')[0].fieldChanged!=undefined){
		document.getElementsByName('scheduleCYLA.Salaries.incCYLA.hPlossCurYrSetoff')[0].fieldChanged=undefined;
	}

	if(document.getElementsByName('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff')[0].fieldChanged!=undefined){
		document.getElementsByName('scheduleCYLA.Salaries.incCYLA.othSrcLossNoRaceHorseSetoff')[0].fieldChanged=undefined;
	}
	
	if(document.getElementsByName('scheduleCYLA.stcg.incCYLA.hPlossCurYrSetoff')[0].fieldChanged!=undefined){
		document.getElementsByName('scheduleCYLA.stcg.incCYLA.hPlossCurYrSetoff')[0].fieldChanged=undefined;
	}
	if(document.getElementsByName('scheduleCYLA.ltcg.incCYLA.hPlossCurYrSetoff')[0].fieldChanged!=undefined){
		document.getElementsByName('scheduleCYLA.ltcg.incCYLA.hPlossCurYrSetoff')[0].fieldChanged=undefined;
	}
	if(document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.hPlossCurYrSetoff')[0].fieldChanged!=undefined){
		document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.hPlossCurYrSetoff')[0].fieldChanged=undefined;
	}
	if(document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.hPlossCurYrSetoff')[0].fieldChanged!=undefined){
		document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.hPlossCurYrSetoff')[0].fieldChanged=undefined;
	}
	
	if(document.getElementsByName('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff')[0].fieldChanged!=undefined){
		document.getElementsByName('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff')[0].fieldChanged=undefined;
	}
	if(document.getElementsByName('scheduleCYLA.stcg.incCYLA.othSrcLossNoRaceHorseSetoff')[0].fieldChanged!=undefined){
		document.getElementsByName('scheduleCYLA.stcg.incCYLA.othSrcLossNoRaceHorseSetoff')[0].fieldChanged=undefined;
	}
	if(document.getElementsByName('scheduleCYLA.ltcg.incCYLA.othSrcLossNoRaceHorseSetoff')[0].fieldChanged!=undefined){
		document.getElementsByName('scheduleCYLA.ltcg.incCYLA.othSrcLossNoRaceHorseSetoff')[0].fieldChanged=undefined;
	}
		
	if(document.getElementsByName('scheduleCYLA.stcg.incCYLA.hPlossCurYrSetoff')[0].oldvalue!=undefined){
		document.getElementsByName('scheduleCYLA.stcg.incCYLA.hPlossCurYrSetoff')[0].oldvalue=undefined;
	}
	if(document.getElementsByName('scheduleCYLA.ltcg.incCYLA.hPlossCurYrSetoff')[0].oldvalue!=undefined){
		document.getElementsByName('scheduleCYLA.ltcg.incCYLA.hPlossCurYrSetoff')[0].oldvalue=undefined;
	}
	if(document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.hPlossCurYrSetoff')[0].oldvalue!=undefined){
		document.getElementsByName('scheduleCYLA.othSrcInclRaceHorse.incCYLA.hPlossCurYrSetoff')[0].oldvalue=undefined;
	}
	if(document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.hPlossCurYrSetoff')[0].oldvalue!=undefined){
		document.getElementsByName('scheduleCYLA.profitFrmRaceHorse.incCYLA.hPlossCurYrSetoff')[0].oldvalue=undefined;
	}
	
	if(document.getElementsByName('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff')[0].oldvalue!=undefined){
		document.getElementsByName('scheduleCYLA.houseProperty.incCYLA.othSrcLossNoRaceHorseSetoff')[0].oldvalue=undefined;
	}
	if(document.getElementsByName('scheduleCYLA.stcg.incCYLA.othSrcLossNoRaceHorseSetoff')[0].oldvalue!=undefined){
		document.getElementsByName('scheduleCYLA.stcg.incCYLA.othSrcLossNoRaceHorseSetoff')[0].oldvalue=undefined;
	}
	if(document.getElementsByName('scheduleCYLA.ltcg.incCYLA.othSrcLossNoRaceHorseSetoff')[0].oldvalue!=undefined){
		document.getElementsByName('scheduleCYLA.ltcg.incCYLA.othSrcLossNoRaceHorseSetoff')[0].oldvalue=undefined;
	}
	
	calcITR2();	
}

//To calculate Schedule SI
function calcScheduleSI(){

	var splRateInc1 = document.getElementsByName('scheduleSI.splCodeRateTax[0].splRateInc')[0]; splRateInc1.value = coalesce(splRateInc1.value);
	var taxableInc1 = document.getElementsByName('scheduleSI.splCodeRateTax[0].taxableInc')[0]; 
	var splRateIncTax1 = document.getElementsByName('scheduleSI.splCodeRateTax[0].splRateIncTax')[0]; 
	
	var splRateIncDTAAOS = document.getElementsByName('scheduleSI.splCodeRateTax[1].splRateInc')[0];splRateIncDTAAOS.value = coalesce(splRateIncDTAAOS.value);
	var taxableIncDTAAOS = document.getElementsByName('scheduleSI.splCodeRateTax[1].taxableInc')[0];taxableIncDTAAOS.value = coalesce(taxableIncDTAAOS.value);
	var splRateIncTaxDTAAOS = document.getElementsByName('scheduleSI.splCodeRateTax[1].splRateIncTax')[0];
	
	var splRateInc5BB = document.getElementsByName('scheduleSI.splCodeRateTax[2].splRateInc')[0]; splRateInc5BB.value = coalesce(splRateInc5BB.value);
	var taxableInc5BB = document.getElementsByName('scheduleSI.splCodeRateTax[2].taxableInc')[0]; taxableInc5BB.value = coalesce(taxableInc5BB.value);
	var splRateIncTax5BB = document.getElementsByName('scheduleSI.splCodeRateTax[2].splRateIncTax')[0]; splRateIncTax5BB.value = coalesce(splRateIncTax5BB.value);

	var splRateInc5AC1ab = document.getElementsByName('scheduleSI.splCodeRateTax[3].splRateInc')[0]; splRateInc5AC1ab.value = coalesce(splRateInc5AC1ab.value);
	var taxableInc5AC1ab = document.getElementsByName('scheduleSI.splCodeRateTax[3].taxableInc')[0]; taxableInc5AC1ab.value = coalesce(taxableInc5AC1ab.value);
	var splRateIncTax5AC1ab = document.getElementsByName('scheduleSI.splCodeRateTax[3].splRateIncTax')[0]; splRateIncTax5AC1ab.value = coalesce(splRateIncTax5AC1ab.value);

	
	var exemption = getExemption_SI();
	
	var partbSetoffInc = parseInt(coalescePath('partBTI.totalIncome'),10) - parseInt(coalescePath('partBTI.incChargeTaxSplRate111A112'),10) ;
	
	
	// second :: setoff income with total income - final loss setooff
	if(partbSetoffInc > 0){
	if(partbSetoffInc >= exemption){
		exemption = 0;
	}else{
		exemption = exemption - partbSetoffInc;		
	} }
		
	//Taxable Income autopoulate			
	taxableInc5BB.value=zeroOrMore(splRateInc5BB.value);
	taxableInc5AC1ab.value=zeroOrMore(splRateInc5AC1ab.value);
	taxableIncDTAAOS.value=zeroOrMore(splRateIncDTAAOS.value);

	
	//Column 'Tax thereon' values for fixed rows
	splRateIncTax5BB.value = Math.round((30*eval(parseInt(taxableInc5BB.value,10)))/parseInt('100' ,10));
	splRateIncTax5AC1ab.value = Math.round((10*eval(parseInt(taxableInc5AC1ab.value,10)))/parseInt('100' ,10));
	
	var totSplRateInc = eval(parseInt(coalesce(splRateInc1.value) ,10)) + eval(parseInt(coalesce(splRateIncDTAAOS.value) ,10))
                            + eval(parseInt(coalesce(splRateInc5AC1ab.value) ,10)) + eval(parseInt(coalesce(splRateInc5BB.value) ,10)); 
                           
	var totSplRateIncTax = eval(parseInt(coalesce(splRateIncTax1.value) ,10)) + eval(parseInt(coalesce(splRateIncTax5AC1ab.value) ,10))
						+ eval(parseInt(coalesce(splRateIncTaxDTAAOS.value) ,10)) + eval(parseInt(coalesce(splRateIncTax5BB.value) ,10));
	
	var totTaxableInc= eval(parseInt(coalesce(taxableInc1.value) ,10))+ eval(parseInt(coalesce(taxableInc5BB.value) ,10))
                        + eval(parseInt(coalesce(taxableInc5AC1ab.value) ,10)) + eval(parseInt(coalesce(taxableIncDTAAOS.value) ,10));


	var rowCount1=countRowInTable('scheduleSI.splCodeRateTax','splRateInc');

	for(var i = 4; i < rowCount1; i++) {

		var splCodeValue=document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].splRateInc')[0].value;
		var splRatePercent = document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].splRatePercent')[0].value;
		document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].taxableInc')[0].value=zeroOrMore(coalesce(splCodeValue));
		document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].splRateIncTax')[0].value=Math.round(eval((parseFloat(coalesce(splRatePercent) ,10) * parseInt(coalesce(splCodeValue),10))/parseInt('100' ,10) ));

		totSplRateInc = eval ( parseInt(totSplRateInc ,10) + parseInt( coalesce(splCodeValue) ,10) );
		totSplRateIncTax = eval ( parseInt(totSplRateIncTax ,10) + parseInt( coalesce(document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].splRateIncTax')[0].value) ,10) );
		totTaxableInc=eval ( parseInt(totTaxableInc ,10) + parseInt( coalesce(document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].taxableInc')[0].value) ,10) );
	}
	
	document.getElementsByName('scheduleSI.totSplRateIncTax')[0].value = zeroOrMore(totSplRateIncTax);
	document.getElementsByName('scheduleSI.totSplRateInc')[0].value = zeroOrMore(totSplRateInc);
	document.getElementsByName('scheduleSI.totSplRateTaxableInc')[0].value = zeroOrMore(totTaxableInc);
	
}

//To getExemption schedule SI
function getExemption_SI(){
	var age	= calcAgeCommon201516(document.getElementsByName('partAGEN1.personalInfo.dob')[0]);
	var resStatus = document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0]; //RES , NRI
	var taxPayer = document.getElementsByName('partAGEN1.personalInfo.status')[0];  
	var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value;  
		if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && taxPayer.value=='I' && age > 59 && age < 80 && (resStatus.value=='RES' || resStatus.value=='NOR')){
			return 300000;
		}else if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && taxPayer.value=='I' && age >= 80 && (resStatus.value=='RES'  || resStatus.value=='NOR')){
			return 500000;
		}else if( (taxPayer.value=='I' || taxPayer.value=='H') && (resStatus.value=='RES'  || resStatus.value=='NOR')){
			return 250000;
		}else{
			return 0;
		}
	}

function deleteRowToTableScheduleSI(tableId,noOfRow,last){

	deleteRowTableModified(tableId,noOfRow,last);
	calcScheduleSI();

}

function onEmptySetZero(element){
	
	if(element.value==""){
	
		element.value='0';
	}
	
}

//To calculate Ti Tti
function calculateTiTti(cgosIncome) {
	var varDate = document.getElementsByName('verification.date')[0];
	if(varDate.value=='' || varDate.value==undefined || varDate.value== null){
		var dt = new Date();
		varDate.value= ("00" + dt.getDate()).slice(-2) + '/' + ("00" + (dt.getMonth()+1)).slice(-2)+ '/' + dt.getFullYear() ;
	}
	
	calculatePartBTTI_first(cgosIncome);

}

//To calculatePart BTI
function calculatePartBTI_first(){
try{
//1
var salaries = document.getElementsByName('partBTI.salaries')[0];							
salaries.value =  	coalesceSetRet('scheduleS.incomeChargeable') ;
//2
var incomeFromHP = document.getElementsByName('partBTI.incomeFromHP')[0];							
incomeFromHP.value =  zeroOrMore( coalesceSetRet('scheduleHP.totalIncomeChargeableUnHP') );	

//4 OS 
var otherSrcThanOwnRaceHorse = document.getElementsByName('partBTI.incFromOS.otherSrcThanOwnRaceHorse')[0];
otherSrcThanOwnRaceHorse.value = zeroOrMore(coalesceSetRet('scheduleOS.balanceNoRaceHorse'));

var incChargeSplRate = document.getElementsByName('partBTI.incFromOS.incChargeSplRate')[0];
incChargeSplRate.value = zeroOrMore(coalesceSetRet('scheduleOS.incChargblSplRateOS.totalOSGrossChargblSplRate'));

var fromOwnRaceHorse = document.getElementsByName('partBTI.incFromOS.fromOwnRaceHorse')[0];
fromOwnRaceHorse.value = zeroOrMore(coalesceSetRet('scheduleOS.incFromOwnHorse.balanceOwnRaceHorse'));

var totIncFromOS = document.getElementsByName('partBTI.incFromOS.totIncFromOS')[0];
totIncFromOS.value = eval(parseInt(otherSrcThanOwnRaceHorse.value, 10)
						 + parseInt(incChargeSplRate.value, 10)
						 + parseInt(fromOwnRaceHorse.value, 10)
						 );


//5
document.getElementsByName('partBTI.totalTI')[0].value = eval(
	parseInt(salaries.value, 10)
	+ parseInt(incomeFromHP.value ,10)
	+ parseInt(coalesceSetRet('partBTI.incFromOS.totIncFromOS'),10)
	);	

//6
document.getElementsByName('partBTI.currentYearLoss')[0].value = eval(
	parseInt(coalesceSetRet('scheduleCYLA.totalLossSetOff.totHPlossCurYrSetoff'),10)
	+ parseInt(coalesceSetRet('scheduleCYLA.totalLossSetOff.totOthSrcLossNoRaceHorseSetoff'),10)
	);

//7
document.getElementsByName('partBTI.balanceAfterSetoffLosses')[0].value = eval(
	parseInt(coalesceSetRet('partBTI.totalTI'),10)
	- parseInt(coalesceSetRet('partBTI.currentYearLoss'),10)
	);

//8
document.getElementsByName('partBTI.broughtFwdLossesSetoff')[0].value = zeroOrMore(eval(
	parseInt(coalesceSetRet('scheduleBFLA.totalBFLossSetOff.totBFLossSetoff'),10)
	));

//9
document.getElementsByName('partBTI.grossTotalIncome')[0].value = zeroOrMore(eval(
	parseInt(coalesceSetRet('partBTI.balanceAfterSetoffLosses'),10)
	- parseInt(coalesceSetRet('partBTI.broughtFwdLossesSetoff'),10)
	));

//10
document.getElementsByName('partBTI.incChargeTaxSplRate111A112')[0].value = eval(
	parseInt(coalesceSetRet('scheduleSI.totSplRateInc'),10));		
}catch(e){
	alert(e);
}
}

//To calculatePart BTI
function calculatePartBTI_second(){
try{

//11
var grossIncome = document.getElementsByName('partBTI.grossTotalIncome')[0].value;
var splRate111A112 = document.getElementsByName('partBTI.incChargeTaxSplRate111A112')[0].value;
var totalChapVIADeductions = document.getElementsByName('scheduleVIA.deductUndChapVIA.totalChapVIADeductions')[0].value;
var deductionChapVIA = parseInt(grossIncome)-parseInt(splRate111A112);

if(deductionChapVIA < totalChapVIADeductions){
document.getElementsByName('partBTI.deductionsUnderScheduleVIA')[0].value = deductionChapVIA;
} else {


document.getElementsByName('partBTI.deductionsUnderScheduleVIA')[0].value = zeroOrMore(eval(
	parseInt(coalesceSetRet('scheduleVIA.deductUndChapVIA.totalChapVIADeductions'),10)
	));
	}

//12
document.getElementsByName('partBTI.totalIncome')[0].value = rndOffNrsTen(zeroOrMore(eval(
	parseInt(coalesceSetRet('partBTI.grossTotalIncome'),10)
	- parseInt(coalesceSetRet('partBTI.deductionsUnderScheduleVIA'),10)
	)));
// calling SI before 14
	calcScheduleSI();

//13
document.getElementsByName('partBTI.incomeChargeableTotTax')[0].value = parseInt(coalesceSetRet('scheduleSI.totSplRateTaxableInc'),10);

//14	
var netAgricultureIncomeOrOtherIncomeForRate = document.getElementsByName('partBTI.netAgricultureIncomeOrOtherIncomeForRate')[0];
var newVal15 = eval(
	parseInt(coalesceSetRet('scheduleEI.netAgriIncOrOthrIncRule7'),10)
	);

if(parseInt(newVal15)<=5000){
	newVal15 = 0;
}

if(netAgricultureIncomeOrOtherIncomeForRate.old != newVal15){
netAgricultureIncomeOrOtherIncomeForRate.old = newVal15;
netAgricultureIncomeOrOtherIncomeForRate.value = newVal15;
}		
	
//15
var tempInc = zeroOrMore(eval(
	parseInt(coalesceSetRet('partBTI.totalIncome'),10)
	- parseInt(coalesceSetRet('partBTI.incomeChargeableTotTax'),10)));
if(parseInt(tempInc, 10) > getExemption()){	
document.getElementsByName('partBTI.aggregateIncome')[0].value = zeroOrMore(eval(
	parseInt(tempInc, 10)
	+ parseInt(coalesceSetRet('partBTI.netAgricultureIncomeOrOtherIncomeForRate'),10)
	));
}else{
	document.getElementsByName('partBTI.aggregateIncome')[0].value = 0;
}

//16
document.getElementsByName('partBTI.lossesOfCurrentYearCarriedFwd')[0].value = eval(
	parseInt(coalesceSetRet('scheduleCFL.currentAYloss.lossSummaryDetail.hpLossCF'),10)	
	+ parseInt(coalesceSetRet('scheduleCFL.currentAYloss.lossSummaryDetail.othSrcLossRaceHorseCF'),10)
	);



}catch(e){
	alert(e.stack);
}
}	

//To calculatePart BTTI
function calculatePartBTTI_first(cgosIncome){
try{

		//1
		calculateTaxPayableOnTotalInc('partBTI.aggregateIncome','partBTTI.computationOfTaxLiability.taxPayableOnTI.taxAtNormalRatesOnAggrInc');
		document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.taxAtSpecialRates')[0].value = eval(
			parseInt(coalesceSetRet('scheduleSI.totSplRateIncTax'),10)
			);
		if(coalesceSetRet('partBTI.aggregateIncome') > 0){
			calculateTaxPayableOnTotalInc('partBTI.netAgricultureIncomeOrOtherIncomeForRate','partBTTI.computationOfTaxLiability.taxPayableOnTI.rebateOnAgriInc', true);
		}else{
			setEditableFieldValue(document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.rebateOnAgriInc')[0], 0);
		}
		var taxPayableOnTotInc = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.taxPayableOnTotInc')[0];
		taxPayableOnTotInc.value = eval(
			parseInt(coalesceSetRet('partBTTI.computationOfTaxLiability.taxPayableOnTI.taxAtNormalRatesOnAggrInc'),10)
			+ parseInt(coalesceSetRet('partBTTI.computationOfTaxLiability.taxPayableOnTI.taxAtSpecialRates'),10)
			- parseInt(coalesceSetRet('partBTTI.computationOfTaxLiability.taxPayableOnTI.rebateOnAgriInc'),10)
			);
		if(taxPayableOnTotInc.value < 0){
		taxPayableOnTotInc.value = parseInt('0' ,10);
		}
		var rebate87A = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.rebate87A')[0];
		var taxPayable = coalesceSetRet('partBTTI.computationOfTaxLiability.taxPayableOnTI.taxPayableOnTotInc');
		var resStatus = document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value;
		var totalIncome = coalesceSetRet('partBTI.totalIncome');
		var dtaaInc = document.getElementsByName('scheduleSI.splCodeRateTax[1].splRateInc')[0].value;
		totalIncome = parseInt(totalIncome) + parseInt(coalesce(dtaaInc)); 
		var status = document.getElementsByName('partAGEN1.personalInfo.status')[0].value;
		if(status=='I' && (resStatus=='RES' || resStatus=='NOR') && totalIncome<=500000){
			rebate87A.value = Math.min(parseInt(taxPayable,10),2000);
		} else {
		    rebate87A.value = parseInt('0' ,10);
		}
		
		//3
		var taxPayableOnRebate = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.taxPayable')[0];
		taxPayableOnRebate.value = eval(parseInt(taxPayableOnTotInc.value, 10) -
										parseInt(rebate87A.value, 10));
		//4
		calsurchargeOnAboveCrore(cgosIncome);
		
		//5
		var educationCess = document.getElementsByName('partBTTI.computationOfTaxLiability.educationCess')[0];
		educationCess.value = Math.round(eval(
									parseInt(taxPayableOnRebate.value) + 
									coalesceSetRet('partBTTI.computationOfTaxLiability.taxPayableOnTI.surcharge')
								) * 0.03 ); 
		//6
		var grossTaxLiability = document.getElementsByName('partBTTI.computationOfTaxLiability.grossTaxLiability')[0];
		grossTaxLiability.value = eval(
										parseInt(taxPayableOnRebate.value) +
										coalesceSetRet('partBTTI.computationOfTaxLiability.taxPayableOnTI.surcharge') +
										parseInt(educationCess.value) 
										);

}catch(e){
	alert(e.stack);
}		
}

//To calculate surcharge On Above Crore
function calsurchargeOnAboveCrore(cgosIncome){
	var taxPayable = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.taxPayable')[0];
	var surchargeOnAboveCrore = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.surcharge')[0];
	var totInc = document.getElementsByName('partBTI.totalIncome')[0].value;	totInc = coalesce(totInc);

	var surcharge = 0;
	var totalIncome = document.getElementsByName('partBTI.totalIncome')[0].value;
	var incChargeTaxSplRate111A112 = document.getElementsByName('partBTI.incChargeTaxSplRate111A112')[0].value;
	var taxAtSpecialRates = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.taxAtSpecialRates')[0].value;
	
	var dtaaInc = document.getElementsByName('scheduleSI.splCodeRateTax[1].splRateInc')[0].value;
	var dtaaTax = document.getElementsByName('scheduleSI.splCodeRateTax[1].splRateIncTax')[0].value;
	
	// for surcharge
	
				var taxOnTotInc = parseInt(calculateTaxPayable(totalIncome - incChargeTaxSplRate111A112)) + parseInt(taxAtSpecialRates);  

				var normalInc = getSlabbedIncome(parseInt(totalIncome - incChargeTaxSplRate111A112));
				
				var toBeTaxed = 10000000 - coalesce(dtaaInc);
				
				var rowCount1=countRowInTable('scheduleSI.splCodeRateTax','splRateInc');
				
				var percent5SIInc= 0;
				
				var percent10SIInc= 0;
				
				var percent15SIInc= 0;
				
				var percent20SIInc= 0;
				
				var percent25SIInc= 0;
				
				var percent30SIInc= 0;
				
				var percent50SIInc= 0;
				
				for(var i = 0; i < rowCount1; i++) {

					var splCodeValue=document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].splRateInc')[0].value;
					var splRatePercent = document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].splRatePercent')[0].value;
										
					if(splRatePercent==5){
						
						percent5SIInc=eval(parseInt(percent5SIInc,10) +parseInt(document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].taxableInc')[0].value,10));
						
					} else if(splRatePercent==10){
						
						percent10SIInc=eval(parseInt(percent10SIInc,10)+parseInt(document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].taxableInc')[0].value,10));
						
					} else
					if(splRatePercent==15){
						
						percent15SIInc=eval(parseInt(percent25SIInc,10)+parseInt(document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].taxableInc')[0].value,10));
						
					}else if(splRatePercent==20){
						
						percent20SIInc=eval(parseInt(percent20SIInc,10)+parseInt(document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].taxableInc')[0].value,10));
						
					}else if(splRatePercent==25){
						
						percent25SIInc=eval(parseInt(percent25SIInc,10)+parseInt(document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].taxableInc')[0].value,10));
						
					} else if(splRatePercent==30){
						
						percent30SIInc=eval(parseInt(percent30SIInc,10)+parseInt(document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].taxableInc')[0].value,10));
						
					} 					
					
				}
								
				var cgTax = 0;
				
				var cgTaxed = 0;
				
				var exmptn15 = coalesceSetRet('scheduleSI.splCodeRateTax[2].splRateInc') -
				coalesceSetRet('scheduleSI.splCodeRateTax[2].taxableInc');
				
				var exmptn20 = coalesceSetRet('scheduleSI.splCodeRateTax[3].splRateInc') -
				coalesceSetRet('scheduleSI.splCodeRateTax[3].taxableInc');
				
				var exemption = getExemption() - exmptn15 - exmptn20;
				
								
				var normal10Tax=0;
				
				var normal20Tax=0;
				
				var normal30Tax=0;
				
				var exemptionUsed=0;
				
				if (parseInt(totalIncome - incChargeTaxSplRate111A112)>0) {
					if (parseInt(totalIncome - incChargeTaxSplRate111A112)>= getExemption()){
						exemptionUsed=getExemption();
					}else{
					exemptionUsed=parseInt(totalIncome - incChargeTaxSplRate111A112);
					}

				}

				toBeTaxed = zeroOrMore(parseInt(toBeTaxed - exemptionUsed - exmptn15 - exmptn20));
								
				if(parseInt(percent5SIInc, 10) < parseInt(toBeTaxed, 0)){
					cgTax = (percent5SIInc) * 0.05;
					cgTaxed = percent5SIInc;
					toBeTaxed -= parseInt(percent5SIInc, 0);
				}else{
					cgTax = (toBeTaxed ) * 0.05;
					cgTaxed = toBeTaxed;
					toBeTaxed = 0;
				}
								
				percent10SIInc= parseInt(percent10SIInc,10)+parseInt(normalInc["10"], 10);
	
				if(parseInt(percent10SIInc, 10) < parseInt(toBeTaxed, 0)){
					cgTax  =  parseInt(cgTax, 10) + (percent10SIInc) * 0.1;
					cgTaxed = parseInt(cgTaxed)+ percent10SIInc;
					toBeTaxed -= parseInt(percent10SIInc, 0);
			    }else{
					cgTax = parseInt(cgTax, 10)+(toBeTaxed ) * 0.1;
					cgTaxed =parseInt(cgTaxed)+ toBeTaxed;
					toBeTaxed = 0;
			    }

				if(parseInt(percent15SIInc, 10) < parseInt(toBeTaxed, 0)){
					cgTax =  parseInt(cgTax, 10)+(percent15SIInc) * parseFloat(0.15);
					cgTaxed = parseInt(cgTaxed)+percent15SIInc;
					toBeTaxed -= parseInt(percent15SIInc, 0);
				}else{
					cgTax = parseInt(cgTax, 10)+(toBeTaxed ) * parseFloat(0.15);
					cgTaxed = parseInt(cgTaxed)+ toBeTaxed;
					toBeTaxed = 0;
				}
				
				percent20SIInc= parseInt(percent20SIInc,10) + parseInt(normalInc["20"], 10);

				if(parseInt(percent20SIInc, 10) < parseInt(toBeTaxed, 0)){
					cgTax =  parseInt(cgTax, 10)+(percent20SIInc) * 0.2;
					cgTaxed = parseInt(cgTaxed)+ percent20SIInc;
					toBeTaxed -= parseInt(percent20SIInc, 0);
				}else{
					cgTax = parseInt(cgTax, 10)+(toBeTaxed ) * 0.2;
					cgTaxed = parseInt(cgTaxed)+ toBeTaxed;
					toBeTaxed = 0;
				}
				
				if(parseInt(percent25SIInc, 10) < parseInt(toBeTaxed, 0)){
					cgTax =  parseInt(cgTax, 10)+(percent25SIInc) * 0.25;
					cgTaxed = parseInt(cgTaxed)+ percent25SIInc;
					toBeTaxed -= parseInt(percent25SIInc, 0);
				}else{
					cgTax = parseInt(cgTax, 10)+(toBeTaxed ) * 0.25;
					cgTaxed = parseInt(cgTaxed)+toBeTaxed;
					toBeTaxed = 0;
				}
				
				percent30SIInc= parseInt(percent30SIInc,10)+ parseInt(normalInc["30"], 10);	
				
				if(parseInt(percent30SIInc, 10) < parseInt(toBeTaxed, 0)){
					cgTax =  parseInt(cgTax, 10)+(percent30SIInc) * 0.3;
					cgTaxed = parseInt(cgTaxed)+ percent30SIInc;
					toBeTaxed -= parseInt(percent30SIInc, 0);
				}else{
					cgTax = parseInt(cgTax, 10)+ (toBeTaxed ) * 0.3;
					cgTaxed = parseInt(cgTaxed)+toBeTaxed;
					toBeTaxed = 0;
				}
						
				var normalCutOffInc = 10000000 - parseInt(cgTaxed) - coalesce(dtaaInc);
										
				var taxOnCutOffInc = parseInt(cgTax) + parseInt(coalesce(dtaaTax),10) ;
					
				if( rndOffNrsTen(totInc) > 10000000 ){
					var tempSurcharge = taxPayable.value  * 0.1 ;
					//check if eligible for marginal relief
					var extraInc = rndOffNrsTen(totInc) - 10000000;
					
					if( (taxOnTotInc + tempSurcharge ) > (taxOnCutOffInc + extraInc)){
						var marginalRelief = zeroOrMore(taxOnTotInc + tempSurcharge - (taxOnCutOffInc + extraInc ));
						surcharge = zeroOrMore(tempSurcharge - marginalRelief);
						surcharge  = Math.round(surcharge);
						
					}else {
						surcharge = tempSurcharge;
						surcharge  = Math.round(surcharge);
						}
				} else {
					surcharge = parseInt('0' ,10);
				}
				setEditableFieldValue(surchargeOnAboveCrore, surcharge);
	}

//to calculate Part B TTI
function calculatePartBTTI_second(cgosIncome){
try{

//5
document.getElementsByName('partBTTI.computationOfTaxLiability.netTaxLiability')[0].value = zeroOrMore(eval(
	parseInt(coalesceSetRet('partBTTI.computationOfTaxLiability.grossTaxLiability'),10)
	- parseInt(coalesceSetRet('partBTTI.computationOfTaxLiability.taxRelief.section89'),10)
	));
	
//8
calculateAdvancedTax();
calculateTDS();

//6
calcInterestPayable(cgosIncome);

//8
document.getElementsByName('partBTTI.taxPaid.taxesPaid.totalTaxesPaid')[0].value = eval(
	parseInt(coalesceSetRet('partBTTI.taxPaid.taxesPaid.advanceTax'),10)
	+ parseInt(coalesceSetRet('partBTTI.taxPaid.taxesPaid.selfAssessmentTax'),10)
	+ parseInt(coalesceSetRet('partBTTI.taxPaid.taxesPaid.tds'),10)
	);

//9
document.getElementsByName('partBTTI.taxPaid.balTaxPayable')[0].value = rndOffNrsTen(zeroOrMore(eval(
	parseInt(coalesceSetRet('partBTTI.computationOfTaxLiability.aggregateTaxInterestLiability'),10)
	- parseInt(coalesceSetRet('partBTTI.taxPaid.taxesPaid.totalTaxesPaid'),10)
	)));

//10
document.getElementsByName('partBTTI.refundsDue')[0].value = rndOffNrsTen(zeroOrMore(eval(
	parseInt(coalesceSetRet('partBTTI.taxPaid.taxesPaid.totalTaxesPaid'),10)
	- parseInt(coalesceSetRet('partBTTI.computationOfTaxLiability.aggregateTaxInterestLiability'),10)
	)));
	
if(document.getElementsByName('partBTTI.taxPaid.balTaxPayable')[0].value > 0){
	document.getElementsByName('partAGEN1.filingStatus.taxStatus')[0].value = 'TP';
}else if(document.getElementsByName('partBTTI.refundsDue')[0].value > 0){
	document.getElementsByName('partAGEN1.filingStatus.taxStatus')[0].value = 'TR';
}else{
	document.getElementsByName('partAGEN1.filingStatus.taxStatus')[0].value = 'NT';
}		
	
}catch(e){
	alert(e.stack);
}
}	

//To calculate TaxPayable O nTotal Income
function calculateTaxPayableOnTotalInc(srcElementName, destElementName, forRebate){
        
	var totalIncome = zeroOrMore( parseInt(coalesceSetRet(srcElementName),10));
	var taxPayer = document.getElementsByName('partAGEN1.personalInfo.status')[0];
	//IN-I,HUF-H
	var resStatus 			= document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0]; //RES , NRI 
	
	var age	= calcAge();
	
	var netTxblIncome 		= totalIncome;
	if(forRebate==true){
		netTxblIncome = parseInt(totalIncome, 10) + parseInt(getExemption(), 10);
	}
	
	var tax = 0;
	
	var incTax 				= document.getElementsByName(destElementName)[0];	
	var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value; 
	if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && taxPayer.value=='I' && age > 59 && age < 80 && (resStatus.value=='RES' || resStatus.value=='NOR')){

		if(parseInt(netTxblIncome,10) >= parseInt('0',10) && parseInt(netTxblIncome,10) <= parseInt('300000',10)){
			tax = parseInt('0',10);
		}else if(parseInt(netTxblIncome,10) >= parseInt('300001',10) && parseInt(netTxblIncome,10) <= parseInt('500000',10)){
			tax = Math.round(eval( eval(parseInt(netTxblIncome,10) - parseInt('300000',10) )  * parseFloat('0.1'))) ;
		}else if(parseInt(netTxblIncome,10) >= parseInt('500001',10) && parseInt(netTxblIncome,10) <= parseInt('1000000',10)){
			tax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('500000',10) )* parseFloat('0.2')) + parseInt('20000',10)));
		}else if(parseInt(netTxblIncome,10) >= parseInt('1000001',10)){
			tax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('1000000',10) )* parseFloat('0.3')) + parseInt('120000',10)));
		}
	
	}else if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && taxPayer.value=='I' && age >= 80 && (resStatus.value=='RES' || resStatus.value=='NOR')){
			   
		if(parseInt(netTxblIncome,10) >= parseInt('0',10) && parseInt(netTxblIncome,10) <= parseInt('500000',10)){
			tax = parseInt('0',10);
		}else if(parseInt(netTxblIncome,10) >= parseInt('500001',10) && parseInt(netTxblIncome,10) <= parseInt('1000000',10)){
			tax = Math.round(eval( eval(parseInt(netTxblIncome,10) - parseInt('500000',10) )  * parseFloat('0.2'))) ;
					
		}else if(parseInt(netTxblIncome,10) >= parseInt('1000001',10)){
			tax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('1000000',10) )* parseFloat('0.3')) + parseInt('100000',10)));             
		}
			   
		
	}else if( (taxPayer.value=='I') || taxPayer.value=='H' ){
		
		if(parseInt(netTxblIncome,10) >= parseInt('0',10) && parseInt(netTxblIncome,10) <= parseInt('250000',10)){
			tax = parseInt('0',10);
		}else if(parseInt(netTxblIncome,10) >= parseInt('250001',10) && parseInt(netTxblIncome,10) <= parseInt('500000',10)){
			tax = Math.round(eval( eval(parseInt(netTxblIncome,10) - parseInt('250000',10) )  * parseFloat('0.1'))) ;
		}else if(parseInt(netTxblIncome,10) >= parseInt('500001',10) && parseInt(netTxblIncome,10) <= parseInt('1000000',10)){
			tax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('500000',10) )* parseFloat('0.2')) + parseInt('25000',10)));
		}else if(parseInt(netTxblIncome,10) >= parseInt('1000001',10)){
			tax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('1000000',10) )* parseFloat('0.3')) + parseInt('125000',10)));
		}
		
	}
	
	if(forRebate){
		setEditableFieldValue(incTax,tax);
	}else{
		incTax.value = tax;
	}
}

//To get Exemption
function getExemption(){
var age	= calcAgeCommon201516(document.getElementsByName('partAGEN1.personalInfo.dob')[0]);
var resStatus = document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0]; //RES , NRI
var taxPayer = document.getElementsByName('partAGEN1.personalInfo.status')[0];  
var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value; 
		if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && taxPayer.value=='I' && age > 59 && age < 80 && (resStatus.value=='RES' || resStatus.value=='NOR')){
			return 300000;
		}else if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && taxPayer.value=='I' && age >= 80 && (resStatus.value=='RES' || resStatus.value=='NOR')){
			return 500000;
		}else if( (taxPayer.value=='I') || taxPayer.value=='H' ){
			return 250000;
		}else{
			return 0;
		}
}

//To calculate Advanced Tax
function calculateAdvancedTax(){
	var advanceTax = parseInt('0' ,10) ;
	var selfAssessmentTax = parseInt('0' ,10) ;
	var tab3 = document.getElementById('scheduleIt');
	var allInputTags = tab3.getElementsByTagName('input');
	for(var i = 0; i < allInputTags.length; i++) {
		if(allInputTags[i].name.match("dateDep$")){
			if(checkFirstDateBefore(FY_start_date , allInputTags[i].value) && checkFirstDateBefore(allInputTags[i].value , FY_end_date)){
					advanceTax = eval( parseInt(isNVL(advanceTax) ,10) + parseInt(isNVL(allInputTags[i+2].value) ,10));
				}else if( checkFirstDateBefore(AY_start_date , allInputTags[i].value)){
					selfAssessmentTax = eval(parseInt(isNVL(selfAssessmentTax) ,10) + parseInt(isNVL(allInputTags[i+2].value) ,10)) ;
				}
		}
	}
	document.getElementsByName('partBTTI.taxPaid.taxesPaid.advanceTax')[0].value = advanceTax;
	document.getElementsByName('partBTTI.taxPaid.taxesPaid.selfAssessmentTax')[0].value = selfAssessmentTax;
	return advanceTax;
}

//to calculate Advanced Tax 234A
function calculateAdvancedTax234A(){
	var advanceTax = parseInt('0' ,10) ;
	var selfAssessmentTax = parseInt('0' ,10) ;
	var tab3 = document.getElementById('scheduleIt');
	var allInputTags = tab3.getElementsByTagName('input');
	for(var i = 0; i < allInputTags.length; i++) {
		if(allInputTags[i].name.match("dateDep$")){
			if(checkFirstDateBefore(AY_start_date , allInputTags[i].value) && checkFirstDateBefore(allInputTags[i].value , Filing_dueDate)){
				advanceTax = eval( parseInt(isNVL(advanceTax) ,10) + parseInt(isNVL(allInputTags[i+2].value) ,10));
			}
		}
	}
	return advanceTax;
}
	
//To calculate TDS
function calculateTDS(){
var TDS = parseInt('0' ,10);
var TDS1 = parseInt('0' ,10);
var tab2 = document.getElementById('scheduleTDS1');
var allInputTags = tab2.getElementsByTagName('input');
	for(var i = 0; i < allInputTags.length; i++) {
			if (allInputTags[i].name.match("totalTDSSal$")) {
				if(parseInt(allInputTags[i].value,10) >  parseInt(allInputTags[i-1].value,10) ){
					addError(allInputTags[i],'Total Tax deducted cannot exceed Income chargeable under Salaries',true);
					j.setFieldError(allInputTags[i].name,'Total Tax deducted cannot exceed Income chargeable under Salaries');
					allInputTags[i].value = '0';
					TDS1 = eval(parseInt(TDS1 ,10) + parseInt(isNVL(allInputTags[i].value) ,10));
					}
				else{
					TDS1 = eval(parseInt(TDS1 ,10) + parseInt(isNVL(allInputTags[i].value) ,10));
				}
			}
		}
	var TDS2 = parseInt('0' ,10);
	var tab2 = document.getElementById('scheduleTDS2');
	var allInputTags = tab2.getElementsByTagName('input');
		for(var i = 0; i < allInputTags.length; i++) {
				if (allInputTags[i].name.match("claimOwnHands$")) {
					if(eval(parseInt(coalesce(allInputTags[i].value),10)+parseInt(coalesce(allInputTags[i+1].value),10)) >  eval(parseInt(coalesce(allInputTags[i-1].value),10) + parseInt(coalesce(allInputTags[i-2].value),10))){
						addError(allInputTags[i],'Amount claimed for this year cannot be more than total tax deducted',true);
						j.setFieldError(allInputTags[i].name,'Amount claimed for this year cannot be more than total tax deducted');
						allInputTags[i].value = '0';
						TDS2 = eval(parseInt(TDS2 ,10) + parseInt(isNVL(allInputTags[i].value) ,10));
					}else{
						TDS2 = eval(parseInt(TDS2 ,10) + parseInt(isNVL(allInputTags[i].value) ,10));
					}
					allInputTags[i+2].value = zeroOrMore(parseInt(coalesce(allInputTags[i-2].value)) + parseInt(coalesce(allInputTags[i-1].value))
					- parseInt(coalesce(allInputTags[i].value)) - parseInt(coalesce(allInputTags[i+1].value)));
				}
			}

	TDS=eval(parseInt(TDS1,10)+parseInt(TDS2,10));
	document.getElementsByName('partBTTI.taxPaid.taxesPaid.tds')[0].value = parseInt(TDS,10);
	document.getElementsByName('itr2.scheduleTDS1.tdSonOthThanSal.totalTDSonSalaries')[0].value = parseInt(TDS1,10);
	document.getElementsByName('itr2.scheduleTDS2.tdSonOthThanSal.totalTDSonOthThanSals')[0].value = parseInt(TDS2,10);
	
	return TDS;
}

//To calculate Interest Payable
function calcInterestPayable(cgosIncome){

try{

	var advanceTax = document.getElementsByName('partBTTI.taxPaid.taxesPaid.advanceTax')[0].value;
	var TDSToDisplay = document.getElementsByName('partBTTI.taxPaid.taxesPaid.tds')[0];
	TDSToDisplay.value = coalesce(TDSToDisplay.value);
	var TDS = TDSToDisplay.value;		

	var balTaxPayable = document.getElementsByName('partBTTI.computationOfTaxLiability.netTaxLiability')[0];
	balTaxPayable.value = coalesce(balTaxPayable.value);
	
	var advanceTax234A = calculateAdvancedTax234A();

	var intrst234Aprinciple	;
	if(parseInt(balTaxPayable.value ,10) - parseInt(advanceTax ,10) - parseInt(advanceTax234A ,10) - parseInt(TDS ,10)  < 0){
		intrst234Aprinciple = parseInt('0' ,10);
		}else {

		intrst234Aprinciple = parseInt(balTaxPayable.value ,10) - parseInt(advanceTax ,10)  - parseInt(advanceTax234A ,10) - parseInt(TDS ,10) ;

		// Rounding off to previous hundered
			if(parseInt(intrst234Aprinciple,10) > 100){
				intrst234Aprinciple= Math.floor(parseInt(intrst234Aprinciple,10)/100)*parseInt('100' ,10);
			}
	}
	var currentDate = document.getElementsByName('verification.date')[0].value;
	var filingType = document.getElementsByName('partAGEN1.filingStatus.returnFileSec')[0].value;
	
	if(checkFirstDateBefore(currentDate, getCurrentDate())){
		currentDate = getCurrentDate();
	}
	var actualDate = currentDate;
	var originalFilingDate = document.getElementsByName('partAGEN1.filingStatus.origRetFiledDate')[0].value;
	if((filingType=='17' || filingType=='18' ) && originalFilingDate !=undefined && originalFilingDate!=null && originalFilingDate!=''){
		currentDate = originalFilingDate;
	}
	
	
	var duedate = Int_start_date_234A;
		
	var MonthsAfterDueDate =  calcNoOfMonths(currentDate , duedate);
	
	
	var intrst234A = parseInt(intrst234Aprinciple,10) * parseFloat('0.01') * parseInt(MonthsAfterDueDate) ;
    
	var intrst234B = parseInt('0' ,10);
	var	intrst234C = parseInt('0' ,10);
	
	var age	= calcAgeCommon201516(document.getElementsByName('partAGEN1.personalInfo.dob')[0]);
	var resStatus=document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value;
	var taxPayer = document.getElementsByName('partAGEN1.personalInfo.status')[0].value;
	var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value; 
	
	if(!((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && taxPayer=='I' && (resStatus=='RES' || resStatus=='NOR') && parseInt(age, 10) > parseInt(59, 0))){
	
	var slab1 = parseInt('0' ,10);
	var slab2 = parseInt('0' ,10);
	var slab3 = parseInt('0' ,10);
	var slab4 = parseInt('0' ,10);

		var tab4 = document.getElementById('scheduleIt');
		var allInputTags = tab4.getElementsByTagName('input');
		for(var i = 0; i < allInputTags.length; i++) {
			if (allInputTags[i].name.match("dateDep$")) {
                if(checkFirstDateBefore(FY_start_date , allInputTags[i].value) && checkFirstDateBefore( allInputTags[i].value , slab1_end_date ) ){
					slab1 = eval(parseInt(slab1 ,10) + parseInt(isNVL(allInputTags[i+2].value) ,10));
				}
				if(checkFirstDateBefore(slab2_start_date , allInputTags[i].value) && checkFirstDateBefore( allInputTags[i].value , slab2_end_date ) ){
					slab2 = eval(parseInt(slab2 ,10) + parseInt(isNVL(allInputTags[i+2].value) ,10));
				}
				else if(checkFirstDateBefore(slab3_start_date , allInputTags[i].value) && checkFirstDateBefore( allInputTags[i].value , slab3_end_date ) ){
					slab3 = eval(parseInt(slab3 ,10) + parseInt(isNVL(allInputTags[i+2].value) ,10));
				}
				else if(checkFirstDateBefore(slab4_start_date , allInputTags[i].value) && checkFirstDateBefore( allInputTags[i].value , FY_end_date ) ){
					slab4 = eval(parseInt(slab4 ,10) + parseInt(isNVL(allInputTags[i+2].value) ,10));
				}
			}
		}

	intrst234C = calculate234cIntrst(TDS, 0, [slab1, slab2, slab3, slab4], cgosIncome);

	// ===============Interest234B calculation=======================

	var intrst234Bprinciple;
	var intrst234Bi=parseInt('0',10);
	var noOfMonthsTillSelfasst= parseInt('0',10);
	if(parseInt(balTaxPayable.value,10) - parseInt(TDS,10) >= parseInt('10000' ,10)) {
		if(parseInt(advanceTax,10) < ((parseInt(balTaxPayable.value,10) - parseInt(TDS,10) ) * parseFloat('0.90'))) {

			intrst234Bprinciple = (parseInt(balTaxPayable.value ,10) - parseInt(advanceTax ,10) - parseInt(TDS,10) );

			// Rounding off to previous hundered
			if(parseInt(intrst234Bprinciple,10) > 100){
				intrst234Bprinciple= Math.floor(parseInt(intrst234Bprinciple,10)/100)*parseInt('100' ,10);
			}

			//======== Interest 234B first part calc==========

			var selfAsspaidDates=new Array();
			var selfAsspaidAmts=new Array();
			var x=parseInt('0',10);
			var tempDate=parseInt('0',10);
			var tempAmt=parseInt('0',10);

			currentDate = actualDate;
			// to get all self assesment tax values
			for(var p = 0; p < allInputTags.length; p++) {
				if(allInputTags[p].name.match("dateDep$")){
					if( checkFirstDateBefore(AY_start_date , allInputTags[p].value) && checkFirstDateBefore(allInputTags[p].value, currentDate) ){
						if(allInputTags[p+2].value!=0){
							selfAsspaidDates[x]=allInputTags[p].value;
							selfAsspaidAmts[x]=allInputTags[p+2].value;
							x++;
						}
					}
				}
			}


			if(selfAsspaidDates.length > 1){
				for(var q = 0; q < selfAsspaidDates.length-1; q++) {
					for(var r = q+1; r < selfAsspaidDates.length; r++) {
						if(checkFirstDateBefore(selfAsspaidDates[q], selfAsspaidDates[r])){

						}else{
							tempDate=selfAsspaidDates[q];
							tempAmt=selfAsspaidAmts[q];

							selfAsspaidDates[q]=selfAsspaidDates[r];
							selfAsspaidAmts[q]=selfAsspaidAmts[r];

							selfAsspaidDates[r]=tempDate;
							selfAsspaidAmts[r]=tempAmt;
						}
					}
				}
				var arrLen = selfAsspaidDates.length;
					var lastMonth = 0;
					var lastIndex = -1;
					var lastYear =0;
					for(var q = 0; q < arrLen; q++) {
						if(parseInt(selfAsspaidDates[q].substr(3,2), 10) == lastMonth && parseInt(selfAsspaidDates[q].substr(8,2), 10) == lastYear){
							selfAsspaidAmts[lastIndex] = parseInt(selfAsspaidAmts[lastIndex], 10) + parseInt(selfAsspaidAmts[q], 10);
						}else{
							lastMonth = parseInt(selfAsspaidDates[q].substr(3,2), 10);
							lastYear = parseInt(selfAsspaidDates[q].substr(8,2), 10);
							selfAsspaidAmts[++lastIndex] = selfAsspaidAmts[q];
							selfAsspaidDates[lastIndex] = selfAsspaidDates[q];
						}
					}
					selfAsspaidAmts.length = ++lastIndex;
					selfAsspaidDates.length = lastIndex;
			}

			if(selfAsspaidDates.length==0){
				noOfMonthsTillSelfasst=calcNoOfMonths(currentDate,AY_start_date);
			}else{
				noOfMonthsTillSelfasst=calcNoOfMonths(selfAsspaidDates[0],AY_start_date);
			}

			alert('noOfMonthsTillSelfasst11:::'+parseInt(noOfMonthsTillSelfasst));
			intrst234Bi= parseInt(intrst234Bprinciple,10) * parseFloat('0.01') * parseInt(noOfMonthsTillSelfasst) ;

			alert('dddintrst234Bi::'+intrst234Bi);

			//======== Interest 234B second part calc==========
			var intrst234Bprinciple2=parseInt('0',10);  // intrst234Bprinciple if self assesment is paid
			var noOfMonthsTillSelfasst2;
			var intrst234Bii=parseInt('0',10);
			var partialSelfAssPaid=parseInt('0',10);
			var k=parseInt('0',10);
			var interestFrom;
			var interestTill;

			if(selfAsspaidDates.length!=0){

				for(var i = 0; i < selfAsspaidDates.length; i++) {
					partialSelfAssPaid= eval(parseInt(partialSelfAssPaid ,10) +parseInt(selfAsspaidAmts[i] ,10));

					intrst234Bprinciple2=zeroOrMore(eval(parseInt(balTaxPayable.value ,10) - parseInt(advanceTax ,10) - parseInt(TDS,10) +
							parseInt(intrst234A ,10)+parseInt(intrst234C ,10)+parseInt(intrst234Bi ,10)+parseInt(intrst234Bii ,10)
							-parseInt(partialSelfAssPaid,10)));

					// Rounding off to previous hundered
					if(parseInt(intrst234Bprinciple2,10) > parseInt('100' ,10)){
						intrst234Bprinciple2= Math.floor(parseInt(intrst234Bprinciple2,10)/100)*parseInt('100' ,10);
					}
					//calclulating remaining months to levy interest

					interestTill=currentDate;
					interestFrom=selfAsspaidDates[i];

					if(i != eval(selfAsspaidDates.length-parseInt('1' ,10))){

							for(k=i;k < eval(selfAsspaidDates.length-parseInt('1' ,10)); k++){
								if(selfAsspaidDates[k]!=selfAsspaidDates[k+1]){
									interestTill=selfAsspaidDates[k+1];
									interestFrom=selfAsspaidDates[k];
									k=selfAsspaidDates.length;
								}
							}
					}

					noOfMonthsTillSelfasst2=calcNoOfMonths(interestTill,interestFrom)-parseInt('1' ,10) ;
					if(parseInt(intrst234Bprinciple2,10) < parseInt(intrst234Bprinciple,10)){
						intrst234Bprinciple = intrst234Bprinciple2;
						intrst234Bii= eval(parseInt(intrst234Bii,10) +
							(parseInt(intrst234Bprinciple2,10) * parseFloat('0.01') * parseInt(noOfMonthsTillSelfasst2))) ;
					}else{
						intrst234Bii= eval(parseInt(intrst234Bii,10) +
							(parseInt(intrst234Bprinciple,10) * parseFloat('0.01') * parseInt(noOfMonthsTillSelfasst2))) ;
					}
				}
			}
			intrst234B=eval(parseInt(intrst234Bi,10) +parseInt(intrst234Bii,10));
		}
	}else{
		intrst234B = parseInt('0' ,10);
	}
	}

		intrst234A = parseInt(intrst234A ,10);
		intrst234B = parseInt(intrst234B ,10);
		intrst234C = parseInt(intrst234C ,10);	
	
	var intrstPayUs234A = document.getElementsByName('partBTTI.computationOfTaxLiability.intrstPay.intrstPayUs234A')[0];
	if(intrstPayUs234A.old!=intrst234A){
		intrstPayUs234A.old = intrst234A;
		intrstPayUs234A.value = 	intrst234A;
	}

	var intrstPayUs234B = document.getElementsByName('partBTTI.computationOfTaxLiability.intrstPay.intrstPayUs234B')[0];
	if(intrstPayUs234B.old!=intrst234B){
		intrstPayUs234B.old = intrst234B;
		intrstPayUs234B.value = 	intrst234B;
	}
	
	var intrstPayUs234C = document.getElementsByName('partBTTI.computationOfTaxLiability.intrstPay.intrstPayUs234C')[0];
	if(intrstPayUs234C.old!=intrst234C){
		intrstPayUs234C.old = intrst234C;
		intrstPayUs234C.value = 	intrst234C;
	}
	
var intrstPayable = document.getElementsByName('partBTTI.computationOfTaxLiability.intrstPay.totalIntrstPay')[0]; intrstPayable.value = coalesce(intrstPayable.value);
intrstPayable.value = Math.round(eval(parseInt(intrstPayUs234A.value ,10) + parseInt(intrstPayUs234B.value ,10) + parseInt(intrstPayUs234C.value ,10)));

var balTaxPay = document.getElementsByName('partBTTI.computationOfTaxLiability.netTaxLiability')[0]; balTaxPay.value = coalesce(balTaxPay.value);
var totIntrstPay = document.getElementsByName('partBTTI.computationOfTaxLiability.intrstPay.totalIntrstPay')[0]; totIntrstPay.value = coalesce(totIntrstPay.value);
var totTaxIntrstPay = document.getElementsByName('partBTTI.computationOfTaxLiability.aggregateTaxInterestLiability')[0]; totTaxIntrstPay.value = coalesce(totTaxIntrstPay.value);

totTaxIntrstPay.value = eval(balTaxPay.value) + eval(totIntrstPay.value);

}catch(e){
	alert('Exception in calcInterestPayable() = ' + e.stack);
}
}

//to chec Marginal Relief Applicable
function isMarginalRelfApplcbl(){
	var surcharge = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.surcharge')[0];
	var taxPybl = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.taxPayable')[0];
	if(parseInt(surcharge.value) > 0){
		if(parseInt(surcharge.value * 0.1) != taxPybl.value){
			return true;
		}
	}
	return false;
}

//To calculate 234c Intrst
function calculate234cIntrst(TDS, TCS, slabs, cgosIncome){
		try{
		var slab1 = parseInt(slabs[0] ,10);
		var slab2 = parseInt(slabs[1] ,10);
		var slab3 = parseInt(slabs[2] ,10);
		var slab4 = parseInt(slabs[3] ,10);


		var rebateOnAgriInc = parseInt(coalesceSetRet('partBTTI.computationOfTaxLiability.taxPayableOnTI.rebateOnAgriInc'), 10);
		
		var normalBalIncome = eval(
							parseInt(coalesceSetRet('partBTI.grossTotalIncome')) 
							 - parseInt(coalesceSetRet('partBTI.incFromOS.incChargeSplRate'))
							- parseInt(coalesceSetRet('partBTI.deductionsUnderScheduleVIA'))
							);	
		if(parseInt(rebateOnAgriInc, 10) > parseInt('0', 10)){
			normalBalIncome = eval(parseInt(normalBalIncome, 10) 
			+ parseInt(coalesceSetRet('partBTI.netAgricultureIncomeOrOtherIncomeForRate'), 10));
		}
		
		var dtaa = document.getElementsByName('scheduleSI.splCodeRateTax[1].splRateIncTax')[0].value;
		var exemption30Pct = eval(parseInt(coalesceSetRet('scheduleSI.splCodeRateTax[2].splRateInc')));		
		var exemptionOth111A = parseInt(getExemption()) -  eval(
								+ parseInt(exemption30Pct) 
								);			
		//Calculate tax on CG
		var intrstRates = [0.1030, 0.2060, 0.1545,0.3090];
		var appRateSurcharge = 1;
		var intrstRatesSurchrgd = [0.1133, 0.2266, 0.16995,0.3399];
		
		var totalIncome = coalesceSetRet('partBTI.totalIncome');
		if(parseInt(totalIncome) > 10000000){
			intrstRates = intrstRatesSurchrgd;
			appRateSurcharge = 1.1;
		}
		
		var marginal = isMarginalRelfApplcbl();
		var eduCess = 1.03;
		
		if(marginal){
			eduCess = 1;
			appRateSurcharge = 1;
			intrstRates = [0.1, 0.2, 0.15,0.3];
		}
		
		var totalUpto15Of9 = 0;
		var totalUp16Of9To15Of12 = 0;
		var totalUp16Of12To15Of3 = 0;
		var totalUp16Of3To31Of3 = 0;

		var balTaxPayable = document.getElementsByName('partBTTI.computationOfTaxLiability.netTaxLiability')[0];
		var netTaxLiability = balTaxPayable.value;
		//App Rate
		if(parseInt(normalBalIncome) > parseInt(exemptionOth111A)){
			normalBalIncome = parseInt(normalBalIncome) - parseInt(exemptionOth111A);
			exemptionOth111A = 0;
		}else if(parseInt(normalBalIncome, 0) > 0){
			exemptionOth111A = parseInt(exemptionOth111A) - parseInt(normalBalIncome);
			normalBalIncome = 0;
		}				
		
		//30%
		if(parseInt(normalBalIncome) > parseInt(exemption30Pct)){
			normalBalIncome = parseInt(normalBalIncome) - parseInt(exemption30Pct);
			exemption30Pct = 0;
		}else if(parseInt(normalBalIncome, 0) > 0){
			exemption30Pct = parseInt(exemption30Pct) - parseInt(normalBalIncome);
			normalBalIncome = 0;
		}		
		if(marginal){
			var surcharge = document.getElementsByName('partBTTI.computationOfTaxLiability.taxPayableOnTI.surcharge')[0].value;
			
		 }
		//netTaxLiability = 0;
		 		
		var intrst234Ci = parseInt('0' ,10);
		var intrst234Cii = parseInt('0' ,10);
		var intrst234Ciii = parseInt('0' ,10);
				
		var othExemptions = eval(
			parseInt(rebateOnAgriInc, 10) * 1.03
		);
		
		var dtaa = document.getElementsByName('scheduleSI.splCodeRateTax[1].splRateIncTax')[0].value;
		var siTax = parseInt(coalesceSetRet('scheduleSI.totSplRateIncTax')) - calculatePureSITax()-parseInt(coalesce(dtaa),10);
		siTax = siTax * 1.03;
		
		
		if(( eval(parseInt(balTaxPayable.value ,10) - parseInt(TDS ,10) - parseInt(TCS ,10)) >=  parseInt('10000',10))){
			
			
			var totSplRateIncTax = 0;
			
			if(parseInt(slab1 ,10) < eval((parseInt(netTaxLiability, 10)  - parseInt(TDS ,10)) * parseFloat('0.3'))){
				var tempintrst234Ci = (((parseInt(netTaxLiability, 10) - parseInt(TDS ,10)) * parseFloat('0.3'))  - parseInt(slab1 ,10));
				if(parseInt(tempintrst234Ci,10) > 100){
					tempintrst234Ci= Math.floor(parseInt(tempintrst234Ci,10)/100)*parseInt('100' ,10);
				}
				intrst234Ci=parseInt(tempintrst234Ci,10)* parseFloat('0.01') * parseInt('3' ,10);

			}

			
			if(eval(parseInt(slab1 ,10) + parseInt(slab2 ,10)) < eval((parseInt(netTaxLiability, 10) - parseInt(TDS ,10)) * parseFloat('0.6') )){
				var tempintrst234Cii = (((parseInt(netTaxLiability, 10) - parseInt(TDS ,10)) * parseFloat('0.6') )  -parseInt(slab1 ,10) - parseInt(slab2 ,10) );
				if(parseInt(tempintrst234Cii,10) > 100){
					tempintrst234Cii= Math.floor(parseInt(tempintrst234Cii,10)/100)*parseInt('100' ,10);
				}
				intrst234Cii=parseInt(tempintrst234Cii,10)* parseFloat('0.01') * parseInt('3' ,10) ;
			}

			
			if(eval(parseInt(slab1 ,10) + parseInt(slab2 ,10) + parseInt(slab3 ,10)) < eval((parseInt(netTaxLiability, 10)  - parseInt(TDS ,10)) * parseFloat('1' ,10))){
				var tempintrst234Ciii = (((parseInt(netTaxLiability, 10) - parseInt(TDS ,10)) * parseFloat('1')) - parseInt(slab1 ,10)- parseInt(slab2 ,10) - parseInt(slab3 ,10) );
				if(parseInt(tempintrst234Ciii,10) > 100){
					tempintrst234Ciii= Math.floor(parseInt(tempintrst234Ciii,10)/100)*parseInt('100' ,10);
				}
				intrst234Ciii=parseInt(tempintrst234Ciii,10)* parseFloat('0.01') * parseInt('1' ,10) ;
			}	
			
		}
		else {
			 intrst234Ci = parseInt('0',10);
			 intrst234Cii = parseInt('0',10);
			 intrst234Ciii = parseInt('0',10);
			 
		}

		
		intrst234C = eval(parseInt(intrst234Ci ,10) + parseInt(intrst234Cii ,10) + parseInt(intrst234Ciii ,10));
		
		}catch(e){
			alert('Error in calculate234cIntrst: ' + e.stack);
		}
		
		return intrst234C;

}

//To calculate Slabbed Tax
function calculateSlabbedTax(netTxblIncome, dontAddExemption){
			var incTax = 0;
			if(!dontAddExemption){
			netTxblIncome = parseInt(netTxblIncome) + getExemption();
			}
			var age = calcAge();
			var resStatus=document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value;
			var status=document.getElementsByName('partAGEN1.personalInfo.status')[0].value; 
			var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value; 
			
			if( (pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && status == 'I' && (resStatus=='RES' || resStatus =='NOR') && parseInt(age, 10) > 59 && parseInt(age, 10) < 80 ){
				if(parseInt(netTxblIncome,10) >= parseInt('0',10) && parseInt(netTxblIncome,10) <= parseInt('300000',10)){
					incTax = parseInt('0',10);
				}else if(parseInt(netTxblIncome,10) >= parseInt('300001',10) && parseInt(netTxblIncome,10) <= parseInt('500000',10)){
					incTax = Math.round(eval( eval(parseInt(netTxblIncome,10) - parseInt('300000',10) )  * parseFloat('0.1'))) ;
				}else if(parseInt(netTxblIncome,10) >= parseInt('500001',10) && parseInt(netTxblIncome,10) <= parseInt('1000000',10)){
					incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('500000',10) )* parseFloat('0.2')) + parseInt('20000',10)));
				}else if(parseInt(netTxblIncome,10) >= parseInt('1000001',10)){
					incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('1000000',10) )* parseFloat('0.3')) + parseInt('120000',10)));
				}
			}
			else if( (pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && status == 'I' && (resStatus=='RES' || resStatus =='NOR') && parseInt(age, 10) >= 80 ){
				if(parseInt(netTxblIncome,10) >= parseInt('0',10) && parseInt(netTxblIncome,10) <= parseInt('500000',10)){
					incTax = parseInt('0',10);
				}else if(parseInt(netTxblIncome,10) >= parseInt('500001',10) && parseInt(netTxblIncome,10) <= parseInt('1000000',10)){
					incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('500000',10) )* parseFloat('0.2'))));
				}else if(parseInt(netTxblIncome,10) >= parseInt('1000001',10)){
					incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('1000000',10) )* parseFloat('0.3')) + parseInt('100000',10)));
				}
			}else{
				if(parseInt(netTxblIncome,10) >= parseInt('0',10) && parseInt(netTxblIncome,10) <= parseInt('250000',10)){
					incTax = parseInt('0',10);
				}else if(parseInt(netTxblIncome,10) >= parseInt('250001',10) && parseInt(netTxblIncome,10) <= parseInt('500000',10)){
					incTax = Math.round(eval( eval(parseInt(netTxblIncome,10) - parseInt('250000',10) )  * parseFloat('0.1'))) ;
				}else if(parseInt(netTxblIncome,10) >= parseInt('500001',10) && parseInt(netTxblIncome,10) <= parseInt('1000000',10)){
					incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('500000',10) )* parseFloat('0.2')) + parseInt('25000',10)));
				}else if(parseInt(netTxblIncome,10) >= parseInt('1000001',10)){
					incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('1000000',10) )* parseFloat('0.3')) + parseInt('125000',10)));
				}
			}
			return incTax;
}

//To apply Exemption
function applyExemption(original, exemption, appRate){
		var remaining = exemption;
		var nonZero = 0;
		for(var i=original.length-1;i>=0;i--){
			if(i>0 && (i<original.length-1 || (appRate && i<original.length))){
				original[i] = original[i]-original[i-1];
			}
			if(original[i]!=0){
				nonZero++;
			}
		}
		if(nonZero==0 ){
			return original;
		}
		var total = 0;
		for(var i=0;i<original.length;i++){
			if(parseInt(original[i], 10)>parseInt(0, 10)){
				var part = remaining / nonZero--;
				if(parseInt(original[i]) > parseInt(part)){
					remaining = remaining - part;
					original[i] = original[i] - part;
				}else{
					remaining = remaining - original[i];
					original[i] = 0;
				}
			}
			if(i>0 && (i<original.length-1 || (appRate && i<original.length))){
				original[i] = original[i] + original[i-1];
			}
			total = eval(parseInt(total, 10) + parseInt(original[i]));
		}
		if(parseInt(remaining,10) > parseInt(0, 10) && total > parseInt(0,10)){
			original = applyExemption(original, remaining);
		}
		
	return original;
}


function rndOffNrsTen(newVar){

    if(  parseInt(newVar.toString().charAt(newVar.toString().length-1),10) >= parseInt('5',10)){
            newVar = eval(Math.floor(eval(parseInt(newVar,10) / parseInt('10',10))) * parseInt('10',10));
            newVar = eval(parseInt(newVar,10) + parseInt('10',10));

            return newVar;
    }else{
            newVar = eval(Math.floor(eval(parseInt(newVar,10) / parseInt('10',10))) * parseInt('10',10));

            return newVar;
    }

}	



//to calculate schedule HP
function scheduleHPCalcFor2(){
	var totHp=eval(parseInt(document.getElementById('scheduleHPLast').cells[0].textContent)-1);
	var total=0;
    var thirtyPercentOfBalanceTemp = 0;

	for(var i=0;i<totHp;i++){

		document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.totalUnrealizedAndTax')[0].value=
		eval(parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.rentNotRealized')[0].value==""?0:
		coalesceSetRet('scheduleHP.propertyDetails['+i+'].rentdetails.rentNotRealized')
		) 
		+ parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.localTaxes')[0].value==""?0:
		coalesceSetRet('scheduleHP.propertyDetails['+i+'].rentdetails.localTaxes')
		));


		document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.balanceALV')[0].value=
		eval(parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.annualLetableValue')[0].value==""?0:
		coalesceSetRet('scheduleHP.propertyDetails['+i+'].rentdetails.annualLetableValue')
		) - 
		parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.totalUnrealizedAndTax')[0].value==""?0:
		coalesceSetRet('scheduleHP.propertyDetails['+i+'].rentdetails.totalUnrealizedAndTax')
		));


		var incomeChargbleOwnHands = document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.incomeChargbleOwnHands')[0];
		setEditableFieldValue(incomeChargbleOwnHands, Math.round(eval(parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.balanceALV')[0].value) * (parseFloat(document.getElementsByName('scheduleHP.propertyDetails['+i+'].asseseeShareProperty')[0].value)) /100 )));
		
                  thirtyPercentOfBalanceTemp = Math.round(eval(parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.incomeChargbleOwnHands')[0].value==""?0:document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.incomeChargbleOwnHands')[0].value) * 0.3 ));
			if( parseInt(thirtyPercentOfBalanceTemp ,10) >0 ){
				document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.thirtyPercentOfBalance')[0].value = thirtyPercentOfBalanceTemp;
			}else{
				document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.thirtyPercentOfBalance')[0].value = parseInt(0,10);
			}

		document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.totalDeduct')[0].value=
		eval(parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.thirtyPercentOfBalance')[0].value==""?0:
		coalesceSetRet('scheduleHP.propertyDetails['+i+'].rentdetails.thirtyPercentOfBalance')
		) 
		+ parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.intOnBorwCap')[0].value==""?0:
		coalesceSetRet('scheduleHP.propertyDetails['+i+'].rentdetails.intOnBorwCap')
		));

		document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.incomeOfHP')[0].value=
		eval(parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.balanceALV')[0].value==""?0:coalesce(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.incomeChargbleOwnHands')[0].value)) - parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.totalDeduct')[0].value==""?0:document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.totalDeduct')[0].value));

		total=eval(parseInt(total) + parseInt(document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.incomeOfHP')[0].value));
		
	}

	document.getElementsByName('scheduleHP.totalIncomeChargeableUnHP')[0].value = eval(parseInt(document.getElementsByName('scheduleHP.rentOfEarlierYrSec25AandAA')[0].value==""?0:document.getElementsByName('scheduleHP.rentOfEarlierYrSec25AandAA')[0].value) + parseInt(document.getElementsByName('scheduleHP.rentArearsSec25BAfter30PcDeduct')[0].value==""?0:document.getElementsByName('scheduleHP.rentArearsSec25BAfter30PcDeduct')[0].value) + parseInt(total));


}

//To check LetOut
function isLetOut(){

	var totHp=eval(parseInt(document.getElementById('scheduleHPLast').cells[0].textContent)-1);
		for(var i=0;i<totHp;i++){
			var tempName='scheduleHP.propertyDetails['+i+'].ifLetOut';
			var val=document.getElementsByName(tempName)[0].value;

			if(val=='Y'){
				
				$('#scheduleHPTenant'+eval(parseInt(i)+1)).find(':input').prop('disabled', false);
				document.getElementsByName('scheduleHP.propertyDetails['+i+'].coTenants[0].coTenantsSNo')[0].value = 1;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.annualLetableValue')[0].disabled=false;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.rentNotRealized')[0].disabled=false;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.localTaxes')[0].disabled=false;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.incomeChargbleOwnHands')[0].disabled=true;
			}
			else if(val=='D'){
				$('#scheduleHPTenant'+eval(parseInt(i)+1)).find('[type=\"checkbox\"]').attr('checked','checked');
				deleteRowTable('scheduleHPTenant'+eval(parseInt(i)+1),1,1);
				$('#scheduleHPTenant'+eval(parseInt(i)+1)).find(':input').prop('disabled', true);
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.annualLetableValue')[0].disabled=false;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.rentNotRealized')[0].disabled=false;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.localTaxes')[0].disabled=false;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.incomeChargbleOwnHands')[0].disabled=true;
			}
			else{
				
				$('#scheduleHPTenant'+eval(parseInt(i)+1)).find('[type=\"checkbox\"]').attr('checked','checked');
				deleteRowTable('scheduleHPTenant'+eval(parseInt(i)+1),1,1);
				$('#scheduleHPTenant'+eval(parseInt(i)+1)).find(':input').prop('disabled', true);
				
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.annualLetableValue')[0].disabled=true;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.annualLetableValue')[0].value='';
				document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.rentNotRealized')[0].disabled=true;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.rentNotRealized')[0].value='';
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.localTaxes')[0].disabled=true;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.localTaxes')[0].value='';
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.incomeChargbleOwnHands')[0].disabled=true;
	            document.getElementsByName('scheduleHP.propertyDetails['+i+'].rentdetails.incomeChargbleOwnHands')[0].value='';
			}
				
		}
		
	}

//to check CoOwned
function isCoOwned(){
var totHp=eval(parseInt(document.getElementById('scheduleHPLast').cells[0].textContent)-1);

	for(var i=0;i<totHp;i++){
		var tempName='scheduleHP.propertyDetails['+i+'].propCoOwnedFlg';
		var val=document.getElementsByName(tempName)[0].value;
		var assessePercentShareProp = document.getElementsByName('scheduleHP.propertyDetails['+i+'].asseseeShareProperty')[0];
		if(val=='YES'){
			$('#scheduleHP'+eval(parseInt(i)+1)).find(':input').prop('disabled', false);
			document.getElementsByName('scheduleHP.propertyDetails['+i+'].coOwners[0].coOwnersSNo')[0].value = 1;
			document.getElementsByName('scheduleHP.propertyDetails['+i+'].asseseeShareProperty')[0].disabled=false;
			if(assessePercentShareProp.value==100 || assessePercentShareProp.value==0.0){
				assessePercentShareProp.value = '0';
			}
		}
		else{
			$('#scheduleHP'+eval(parseInt(i)+1)).find('[type=\"checkbox\"]').attr('checked','checked');
			deleteRowTable('scheduleHP'+eval(parseInt(i)+1),1,1);
			$('#scheduleHP'+eval(parseInt(i)+1)).find(':input').prop('disabled', true);
			assessePercentShareProp.disabled=true;
			if(val=='NO'){
				assessePercentShareProp.value='100';
			}else{
				assessePercentShareProp.value='0.0';
			}
		}
	}
}


function convertPercentToDecimal(element){

	var fieldVal=element.value;
	if(fieldVal.indexOf('%') !='-1'){
		fieldVal=fieldVal.substring(0,fieldVal.indexOf('%'));
		fieldVal=Math.round(fieldVal);
		element.value=fieldVal/100;

	}

}

//To calculate  total Amount Of Schedule TR
function totAmtOfSchedTRFor2(tableId){
		
	    var table=document.getElementById('scheduleTR');
	    var noOfRows=table.rows.length;
	    var totTaxPaidOutsideInd = parseInt('0' ,10);
		var totReliefAvailable = parseInt('0' ,10);
		var totReliefAvailable9090A = parseInt('0' ,10);
		var totReliefAvailable91 = parseInt('0' ,10);
	      
        for(var i=0;i<eval(parseInt(noOfRows,10)-4);i++){
	        if(document.getElementsByName('scheduleTR1.scheduleTR['+i+'].relavantArticleDTAA')[0].value=='91'){
	        	totReliefAvailable91=eval(totReliefAvailable91+ parseInt(coalesce(document.getElementsByName('scheduleTR1.scheduleTR['+i+'].taxReliefOutsideIndia')[0].value),10));
	        
	        } else if(document.getElementsByName('scheduleTR1.scheduleTR['+i+'].relavantArticleDTAA')[0].value=='90' ||
		        document.getElementsByName('scheduleTR1.scheduleTR['+i+'].relavantArticleDTAA')[0].value=='90A'){
	        	totReliefAvailable9090A=eval(totReliefAvailable9090A+parseInt(coalesce(document.getElementsByName('scheduleTR1.scheduleTR['+i+'].taxReliefOutsideIndia')[0].value),10));
	        }
	        
	        totTaxPaidOutsideInd = eval(parseInt(totTaxPaidOutsideInd,10) + parseInt(coalesce(document.getElementsByName('scheduleTR1.scheduleTR['+i+'].taxPaidOutsideIndia')[0].value,10)));
	        totReliefAvailable = eval(parseInt(totReliefAvailable,10) + parseInt(coalesce(document.getElementsByName('scheduleTR1.scheduleTR['+i+'].taxReliefOutsideIndia')[0].value,10)));
        
        }
        
        document.getElementsByName('scheduleTR1.totalIncomeOutIndia')[0].value = totReliefAvailable9090A;
        document.getElementsByName('scheduleTR1.totalIncomeOutIndiaDTAA')[0].value = totReliefAvailable91;
        document.getElementsByName('scheduleTR1.totTaxPaidDeclaredInFSI')[0].value = totTaxPaidOutsideInd;
        document.getElementsByName('scheduleTR1.totReliefClaimUs9090A')[0].value = totReliefAvailable;

}



function delRowSchedFSIFor6(tableId,noOfRow,last){

		deleteRowTable(tableId,noOfRow,last);

	}

	
	
	function zeroOrLess(val){
	if(parseInt(val, 10) > 0 ){
		return 0;
	}
	return parseInt(val, 10);
}	

//To validate Schedule HP
function validateScheduleHP(){
	var tab = document.getElementById('scheduleHPMain');
	var allInputTags = tab.getElementsByTagName('select');
	var count = 0;
	for(var i=0; i<allInputTags.length; i++ ){
		if(allInputTags[i].name.match("ifLetOut$")){
			if(allInputTags[i].value=="N"){
				if(++count > 1){
					j.setFieldError(allInputTags[i].name,'Where there is more than one Self occupied House property(SOP) , one of them shall be treated as SOP and all other House properties shall be either deemed to be let out or let out');
					break;
				}
			}
		}
	}
}

//To validate Schedule TR
function validateScheduleTR(tableId) {
	var tab = document.getElementById(tableId);
	var allInputTags = tab.getElementsByTagName('input');
	
	for(var i = 0; i < allInputTags.length; i++) {
		if (allInputTags[i].name.match("totTaxIncScheduleFSI$")) {
								
			if(parseInt( coalesce(allInputTags[i].value) ,10) < eval ( parseInt( coalesce(allInputTags[i+1].value)  ,10) + parseInt( coalesce(allInputTags[i+2].value) ,10) )) {
				addError(document.getElementsByName(allInputTags[i].name)[0],'Relief claimed u/s 90/91 (B1 +B2) cannot exceed the total taxes paid.',true);
				j.setFieldError(allInputTags[i].name,'Relief claimed u/s 90/91 (B1 +B2) cannot exceed the total taxes paid.');
			}
		}
	}
}


function addRowSchedTRFor2(tableId,noOfRow,last){

		addRowToTable(tableId,noOfRow,last);
		totAmtOfSchedTRFor2(tableId);

	}

function delRowSchedTRFor2(tableId,noOfRow,last){

		deleteRowTable(tableId,noOfRow,last);
		totAmtOfSchedTRFor2(tableId);

	}
	
	
	//To disable Schedule FSI
	function disableScheduleFSI(){

	var tab = document.getElementById('scheduleFSI');
	var allInputTags = tab.getElementsByTagName('input');
	var selectTags=tab.getElementsByTagName('select');
	var resStatus=document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value;
	
	for(var i = 0; i < allInputTags.length; i++) {
		if(resStatus=='RES'){			
			allInputTags[i].disabled=false;
			allInputTags[i].readOnly=false;		
			
			if (allInputTags[i].name.match("totalCountryWise$")){
				allInputTags[i].disabled=true;
				allInputTags[i].readOnly=true;
			}
			
		}else{
		
			allInputTags[i].disabled=true;
			allInputTags[i].readOnly=true;
			allInputTags[i].value="";	
			
	
		}
	}
	for(var i = 0; i < selectTags.length; i++){
		if(resStatus=='RES'){
			
			selectTags[i].disabled=false;		
		}else{			
			selectTags[i].disabled=true;
			selectTags[i].value="";
		}
		
	}
	
	if(resStatus=='RES'){
		document.getElementsByName('itrScheduleFSI.totalIncomeOutIndiaDTAA')[0].readOnly=false;
		
	}else{
	
		document.getElementsByName('itrScheduleFSI.totalIncomeOutIndia')[0].readOnly=true;
		document.getElementsByName('itrScheduleFSI.totalIncomeOutIndiaDTAA')[0].readOnly=true;
		document.getElementsByName('itrScheduleFSI.totalIncomeOutIndiaWoDTAA')[0].readOnly=true;
		document.getElementsByName('itrScheduleFSI.totalIncomeOutIndia')[0].value='';
		document.getElementsByName('itrScheduleFSI.totalIncomeOutIndiaDTAA')[0].value='';
		document.getElementsByName('itrScheduleFSI.totalIncomeOutIndiaWoDTAA')[0].value='';
		$('#scheduleFSI').find('[type=\"checkbox\"]').attr('checked','checked');
		deleteRowTable('scheduleFSI',1,2);		
	}
	document.getElementsByName('itrScheduleFSI.totIncFromSal')[0].readOnly=true;
	document.getElementsByName('itrScheduleFSI.totIncFromHPPartBTIA')[0].readOnly=true;
	document.getElementsByName('itrScheduleFSI.totIncBusinessPartBTIB')[0].readOnly=true;
	document.getElementsByName('itrScheduleFSI.totIncCapGainPartBTIC')[0].readOnly=true;
	document.getElementsByName('itrScheduleFSI.totIncOthSrcPartBTID')[0].readOnly=true;
	document.getElementsByName('itrScheduleFSI.totalAmtCountryWise')[0].readOnly=true;

}

//To check schedule TR or FSI Mandatory
function checkTRFSIMandatory(){
	
	var trFilled= checkRowBlank('scheduleTR', 3, 1);
	var fsiFilled=checkFSIRowBlank('scheduleFSI', 3, 1);
	var resStatus=document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value;
	if(resStatus=='RES'){
	if(!trFilled && fsiFilled ){
		
		j.setFieldError('itrScheduleFSI.scheduleFSI[0].countryCode','Schedule FSI is mandatory as you have filled schedule TR');
		addErrorXHTML('','Schedule FSI is mandatory as you have filled schedule TR');
	}
	}
}

function checkFSIRowBlank(tableId, noOfRow, last){
	try{
	var tab = document.getElementById(tableId);
	var rowCount = tab.rows.length;
	var trOfLastRow = tab.getElementsByTagName('tr')[rowCount - noOfRow];
	var allInputTags = trOfLastRow.getElementsByTagName('input');
	var allSelectTags = trOfLastRow.getElementsByTagName('select');
	var allTextareaTags = trOfLastRow.getElementsByTagName('textarea');
	var isRowBlank = true;
	
	for ( var i = 0; i < allInputTags.length; i++) {
		if(!allInputTags[i].name.match(".chosenCheckBox$")){
			if(allInputTags[i] != undefined || allInputTags[i].value != null){
				if((allInputTags[i].getAttribute("readonly") == null ) || 
					(allInputTags[i].getAttribute("readonly") != 'readonly')){
						if( allInputTags[i].parentNode.style.display != "none"  && allInputTags[i].getAttribute('type')!='hidden' ){
							var str = allInputTags[i].value.replace(/^\s+|\s+$/g,'');	
							
							if(!allInputTags[i].name.match("totalCountryWise$")){
							if(str!=''){
								isRowBlank = false;
								break;
							}
							}
						}
				}
			}
		}
	}
	
	for ( var i = 0; i < allTextareaTags.length; i++) {
		if(allTextareaTags[i] != undefined || allTextareaTags[i].value != null ){
			var str = allTextareaTags[i].value.replace(/^\s+|\s+$/g,'');
			if(str!=''){
				isRowBlank = false;
				break;
			}
		}
	}
	
	for ( var i = 0; i < allSelectTags.length; i++) {
		if(allSelectTags[i].value != '-1' && allSelectTags[i].value != ''){
			isRowBlank = false;
			break;
		}
	}
	return isRowBlank;
	}catch(e){
		alert('Exception in checkFSIRowBlank method::'+e);
	}
	
}

//To validate schedule HP Rent
function validateHPRent(){
    
	var tab=document.getElementById('scheduleHPMain');
	var allInputTags = tab.getElementsByTagName('input');
		
	for(var i = 0; i < allInputTags.length; i++) {
		if (allInputTags[i].name.match("rentdetails.annualLetableValue$")) {
				if( parseInt(allInputTags[i+1].value,10) > parseInt(allInputTags[i].value ,10)) {
					
					addError(allInputTags[i+1],   
							'Rent not realized cannot exceed Annual Letable Value',true);
						j.setFieldError(allInputTags[i+1].name,'Rent not realized cannot exceed Annual Letable Value');
						break;
				}					
		}
	}
	
}

//To add Schedule HP
function addScheduleHP(){
	
	var mainTable=document.getElementById('scheduleHPMain').rows;
	var tobeInsertBefore=document.getElementById('scheduleHPAddRow');
	var flag=false;
	var totRow=document.getElementById('scheduleHPLast').cells[0].textContent;
	
	var iterate=eval(parseInt(totRow)-1);
	for(var i=0;i<mainTable.length;i++){
	var cloneNode=mainTable[i].cloneNode(true);
		if(mainTable[i].id =='scheduleHP1st'){
		flag=true;
		cloneNode.cells[0].innerHTML=totRow;
		}
		if(mainTable[i].id == 'coOwnerTr'){
			cloneNode.getElementsByTagName('table')[0].setAttribute('id','scheduleHP'+totRow);
			cloneNode.getElementsByTagName('img')[0].setAttribute('onclick','addRowToTableSchHp('+'\'scheduleHP'+totRow+'\',2,1,this);');
			cloneNode.getElementsByTagName('img')[1].setAttribute('onclick','deleteRowTable('+'\'scheduleHP'+totRow+'\',1,1)');
			
		}
		
		if(mainTable[i].id == 'coTenantTr'){
			cloneNode.getElementsByTagName('table')[0].setAttribute('id','scheduleHPTenant'+totRow);
			cloneNode.getElementsByTagName('img')[0].setAttribute('onclick','addRowToTableSchHpTenants('+'\'scheduleHPTenant'+totRow+'\',2,1,this);');
			cloneNode.getElementsByTagName('img')[1].setAttribute('onclick','deleteRowTable('+'\'scheduleHPTenant'+totRow+'\',1,1)');
		}
		
	if(flag ){
		
		var cellsTot=cloneNode.cells;
		for(var j=0;j<cellsTot.length;j++){
			cloneNode.cells[j].innerHTML=cloneNode.cells[j].innerHTML.replace('1a',totRow+'a').replace('1b',totRow+'b').replace('1c',totRow+'c').replace('1d',totRow+'d').replace('1e',totRow+'e').replace('1f',totRow+'f').replace('1g',totRow+'g').replace('1h',totRow+'h').replace('1i',totRow+'i').replace('1j',totRow+'j').replace('property 1','property '+totRow).replace('property 1','property '+totRow);
		}
		
		var inputTags=cloneNode.getElementsByTagName('input');
		for(var a=0;a<inputTags.length;a++){
			inputTags[a].name=inputTags[a].name.replace('[0]','['+iterate+']');
			if(inputTags[a].name.indexOf('coOwnersSNo')=='-1'){
			inputTags[a].value='';
			}
			
			if(inputTags[a].name.indexOf('coTenantsSNo')=='-1'){
				inputTags[a].value='';
			}
                        inputTags[a].id=inputTags[a].name.replace(/([\.\[\]])/g,'_').replace(/(__)/g,'_');
                        
                        var blurAttr=inputTags[a].getAttribute('onblur');
            			if(blurAttr!=null){
            				blurAttr=blurAttr+";";
            			}else{
            				blurAttr="";
            			}
            			inputTags[a].setAttribute('onblur',blurAttr+'j.blur(this,this.name,this.value);');
		}
		
		var selectTags=cloneNode.getElementsByTagName('select');
		for(var a=0;a<selectTags.length;a++){
			selectTags[a].name=selectTags[a].name.replace('[0]','['+iterate+']');
			selectTags[a].value='';
			if(selectTags[a].name.indexOf('stateCode')!='-1'){
					selectTags[a].onchange = function(){populatePincode('scheduleHP.propertyDetails['+ iterate +'].addressDetail.stateCode','scheduleHP.propertyDetails['+ iterate +'].addressDetail.pinCode');};
				}
                        selectTags[a].id=selectTags[a].name.replace(/([\.\[\]])/g,'_').replace(/(__)/g,'_');
                        
                        var blurAttr=selectTags[a].getAttribute('onblur');
            			if(blurAttr!=null){
            				blurAttr=blurAttr+";";
            			}else{
            				blurAttr="";
            			}
            			selectTags[a].setAttribute('onblur',blurAttr+'j.blur(this,this.name,this.value);');
		}
		
		var textareaTags=cloneNode.getElementsByTagName('textarea');
		for(var a=0;a<textareaTags.length;a++){
			textareaTags[a].name=textareaTags[a].name.replace('[0]','['+iterate+']');
			textareaTags[a].value='';
                        textareaTags[a].id=textareaTags[a].name.replace(/([\.\[\]])/g,'_').replace(/(__)/g,'_');
                        
                        var blurAttr=textareaTags[a].getAttribute('onblur');
            			if(blurAttr!=null){
            				blurAttr=blurAttr+";";
            			}else{
            				blurAttr="";
            			}
            			textareaTags[a].setAttribute('onblur',blurAttr+'j.blur(this,this.name,this.value);');
		}
		
		document.getElementById('scheduleHPMain').getElementsByTagName('tr')[0].parentNode.insertBefore(cloneNode,tobeInsertBefore);
		}
	if(mainTable[i].id =='scheduleHPEnd'){
		flag=false;
		break;
		}
	}
	var newVal = eval( parseInt(totRow) + 1);
	var newText='Total (';
	for(var k=1;k<newVal;k++){
		newText=newText+k+'j +';
	}
	newText=newText+newVal+'a +'+newVal+'b )';
	document.getElementById('scheduleHPLast').cells[0].innerHTML=newVal;
	document.getElementById('scheduleHPLast').nextElementSibling.cells[3].innerHTML=newVal+'a';
	document.getElementById('scheduleHPLast').nextElementSibling.nextElementSibling.cells[2].innerHTML=newVal+'b';
	document.getElementById('scheduleHPLast').nextElementSibling.nextElementSibling.nextElementSibling.cells[2].innerHTML=newVal+'c';
	document.getElementById('scheduleHPLast').nextElementSibling.nextElementSibling.nextElementSibling.cells[1].innerHTML=newText;
	
	if($('#scheduleHPAddRow')[0].parentNode.children.length==44){
		$('#delHPButtonId').prop('disabled', true);
	}else if($('#scheduleHPAddRow')[0].parentNode.children.length>44){
		$('#delHPButtonId').prop('disabled', false);
	}
	
	$('#scheduleHPTenant'+eval(parseInt(totRow))).find('[type=\"checkbox\"]').attr('checked','checked');
	deleteRowTable('scheduleHPTenant'+eval(parseInt(totRow)),1,1);
	
	document.getElementsByName('scheduleHP.propertyDetails['+ (parseInt(totRow) - 1)  +'].hpSno')[0].value = totRow;
	var table=document.getElementById('scheduleHPMain');
	modifyRow(table);
	var onchange1=document.getElementsByName('scheduleHP.propertyDetails['+(parseInt(totRow) - 1)+'].propCoOwnedFlg')[0].getAttribute('onchange');
	var onchange2=document.getElementsByName('scheduleHP.propertyDetails['+(parseInt(totRow) - 1)+'].ifLetOut')[0].getAttribute('onchange');
	onchange1=onchange1.substring(0,onchange1.indexOf('('));
	onchange2=onchange2.substring(0,onchange2.indexOf('('));
	window[onchange1]();
	window[onchange2]();
	checkMaxLengthLimit();
}

//to delete Schedule HP 
function delScheduleHPForITR2(){

	if($('#scheduleHPAddRow')[0].parentNode.children.length>46){
		for(var i=0;i<19;i++){
			$('#scheduleHPAddRow')[0].parentNode.deleteRow($('#scheduleHPAddRow')[0].parentNode.children.length-7);
		}
		if($('#scheduleHPAddRow')[0].parentNode.children.length==44){
			$('#delHPButtonId').prop('disabled', true);
		}
	}else if($('#scheduleHPAddRow')[0].parentNode.children.length==44){
		$('#delHPButtonId').prop('disabled', true);
	}
	
	
	($('#scheduleHPLast')[0].children)[0].innerHTML =  parseInt(($('#scheduleHPLast')[0].children)[0].innerHTML) - 1;
	
	
	var totRow=document.getElementById('scheduleHPLast').cells[0].textContent;
	alert('totRow:: '+totRow);
	
	var newVal = eval( parseInt(totRow));
	var newText='Total (';
	for(var k=1;k<newVal;k++){
		newText=newText+k+'i +';
	}
	newText=newText+newVal+'a +'+newVal+'b )';
	document.getElementById('scheduleHPLast').cells[0].innerHTML=newVal;
	document.getElementById('scheduleHPLast').nextElementSibling.cells[3].innerHTML=newVal+'a';
	document.getElementById('scheduleHPLast').nextElementSibling.nextElementSibling.cells[2].innerHTML=newVal+'b';
	document.getElementById('scheduleHPLast').nextElementSibling.nextElementSibling.nextElementSibling.cells[2].innerHTML=newVal+'c';
	document.getElementById('scheduleHPLast').nextElementSibling.nextElementSibling.nextElementSibling.cells[1].innerHTML=newText;
	
	var table=document.getElementById('scheduleHPMain');
			
	modifyRow(table);
	calcITR2();
}

//To set Serial Number
function setSerialNumber(element,header){
	try{
	
	 var tableId=element.getAttribute('onclick').substring(20,element.getAttribute('onclick').lastIndexOf('\''));

	  var index=tableId.substring(10);
	  
	  index=eval(index-1);

	var table = document.getElementById(tableId);
	var noOfRows = table.rows.length;

	for ( var i = 0; i < eval(parseInt(noOfRows, 10) - header); i++) {
	
		document.getElementsByName('scheduleHP.propertyDetails['+index+'].coOwners['+i+'].coOwnersSNo')[0].value=i+1;

		
	}
	}catch(e){
	alert('errror in setSerialNumber method:' +e);
	}
	
}

//To set Serial Number Tenants
function setSerialNumberTenants(element,header){
	try{
	
	 var tableId=element.getAttribute('onclick').substring(27,element.getAttribute('onclick').lastIndexOf('\''));

	  var index=tableId.substring(16);
	  
	  index=eval(index-1);

	var table = document.getElementById(tableId);
	var noOfRows = table.rows.length;

	for ( var i = 0; i < eval(parseInt(noOfRows, 10) - header); i++) {
	
		document.getElementsByName('scheduleHP.propertyDetails['+index+'].coTenants['+i+'].coTenantsSNo')[0].value=i+1;

		
	}
	}catch(e){
	alert('errror in setSerialNumberTenants method:' +e);
	}
	
}



function onChngPCC5A(){
	var typeHP = document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].value;
	if(typeHP=='Y'){
		addErrorXHTML('','You have selected to be governed by Sec 5A. Please Fill Schedule 5A');
	}
	adjustTDS2();
}

function onChngBTTIRefund(){
	var typeHP = document.getElementsByName('partBTTI.assetOutIndiaFlag')[0].value;
	alert(typeHP);
	if(typeHP=='YES'){
		addErrorXHTML('','Schedule FA is mandatory. Ensure all the details in Schedule FA are filled');
	}
}



function getPan(){

var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value;
return pan;
}

//To calculate Tax Payable
function calculateTaxPayable(netTxblIncome){
            
		var taxPayer = document.getElementsByName('partAGEN1.personalInfo.status')[0];
		//IN-I,HUF-H
		var resStatus 			= document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0]; //RES , NRI 
		
		var age	= calcAge();

		var incTax = parseInt('0', 10);	
		var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value; 
		
		if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && taxPayer.value=='I' && age > 59 && age < 80 && (resStatus.value=='RES' || resStatus.value=='NOR')){

			if(parseInt(netTxblIncome,10) >= parseInt('0',10) && parseInt(netTxblIncome,10) <= parseInt('300000',10)){
			incTax = parseInt('0',10);
			}else if(parseInt(netTxblIncome,10) >= parseInt('300001',10) && parseInt(netTxblIncome,10) <= parseInt('500000',10)){
				incTax = Math.round(eval( eval(parseInt(netTxblIncome,10) - parseInt('300000',10) )  * parseFloat('0.1'))) ;
			}else if(parseInt(netTxblIncome,10) >= parseInt('500001',10) && parseInt(netTxblIncome,10) <= parseInt('1000000',10)){
				incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('500000',10) )* parseFloat('0.2')) + parseInt('20000',10)));
			}else if(parseInt(netTxblIncome,10) >= parseInt('1000001',10)){
				incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('1000000',10) )* parseFloat('0.3')) + parseInt('120000',10)));
			}
		
		}else if((pan.substring(3,4)=='P' || pan.substring(3,4)=='p') && taxPayer.value=='I' && age >= 80 && (resStatus.value=='RES' || resStatus.value=='NOR')){
				   
			if(parseInt(netTxblIncome,10) >= parseInt('0',10) && parseInt(netTxblIncome,10) <= parseInt('500000',10)){
				incTax = parseInt('0',10);
			}else if(parseInt(netTxblIncome,10) >= parseInt('500001',10) && parseInt(netTxblIncome,10) <= parseInt('1000000',10)){
				incTax = Math.round(eval( eval(parseInt(netTxblIncome,10) - parseInt('500000',10) )  * parseFloat('0.2'))) ;
						
			}else if(parseInt(netTxblIncome,10) >= parseInt('1000001',10)){
				incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('1000000',10) )* parseFloat('0.3')) + parseInt('100000',10)));             
			}
				   
			
		}else if( (taxPayer.value=='I') || taxPayer.value=='H' ){
			
			if(parseInt(netTxblIncome,10) >= parseInt('0',10) && parseInt(netTxblIncome,10) <= parseInt('250000',10)){
			incTax = parseInt('0',10);
			}else if(parseInt(netTxblIncome,10) >= parseInt('250001',10) && parseInt(netTxblIncome,10) <= parseInt('500000',10)){
				incTax = Math.round(eval( eval(parseInt(netTxblIncome,10) - parseInt('250000',10) )  * parseFloat('0.1'))) ;
			}else if(parseInt(netTxblIncome,10) >= parseInt('500001',10) && parseInt(netTxblIncome,10) <= parseInt('1000000',10)){
				incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('500000',10) )* parseFloat('0.2')) + parseInt('25000',10)));
			}else if(parseInt(netTxblIncome,10) >= parseInt('1000001',10)){
				incTax = Math.round(eval(eval(eval(parseInt(netTxblIncome,10) - parseInt('1000000',10) )* parseFloat('0.3')) + parseInt('125000',10)));
			}
			
		}
		
		return incTax;
		
}

//To check number Of CoOwners
function numberOfCoOwnersCheck(tableId,noRows){
	var tab = document.getElementById(tableId);
	var rowCount = tab.rows.length;
	if(rowCount > noRows) {
	addErrorXHTML('','Cannot insert more than 5 rows',true);
	return false;
	}
	return true;

}

function addRowToTableSchHp(tableId, noOfRow, last,elem) {
	
		
		addRowToTable(tableId,noOfRow,last);
		setSerialNumber(elem,2);
	
}

function addRowToTableSchHpTenants(tableId, noOfRow, last,elem) {
	
	addRowToTable(tableId,noOfRow,last);
	setSerialNumberTenants(elem,2);
}

//To addSchedule SI Row
function addSchSIRow(SecCode,SecCodeValue){
    try{
    var tableId=document.getElementById('scheduleSI');
    var mainTable=document.getElementById('scheduleSI').rows;
    var noOfRows=tableId.rows.length;
    var toInsertBefore=document.getElementById('scheduleSILastRow');
   
    var lastIndex=eval(parseInt(noOfRows,10)-2);
    
    
    
    var cloneNode=mainTable[lastIndex].cloneNode(true);
    var newSlNo=cloneNode.cells[0].textContent;
    
    
    var iterate=eval(parseInt(newSlNo,10)-1);
    ;
    cloneNode.cells[0].innerHTML=eval(parseInt(newSlNo,10)+1);
    //getSection
    cloneNode.cells[1].innerHTML=getSectionTextMap(SecCode);
    var inputTags=cloneNode.getElementsByTagName('input');
		for(var a=0;a<inputTags.length;a++){
                   
			inputTags[a].name=inputTags[a].name.replace('['+iterate+']','['+lastIndex+']');
			
                        inputTags[a].id=inputTags[a].name.replace(/([\.\[\]])/g,'_').replace(/(__)/g,'_');
                        //Display Section Rate
                        inputTags[1].value=getSectionTaxRate(SecCode);
                        //Income
                        inputTags[2].value=zeroOrMore(parseInt(SecCodeValue,10));
                        
                        
                        if(inputTags[a].getAttribute('type')=='hidden' && inputTags[a].name.match("secCode$")){
                            inputTags[a].value=SecCode;
                        }
                        
                        
                        var blurAttr=inputTags[a].getAttribute('onblur');
            			if(blurAttr!=null){
            				blurAttr=blurAttr+";";
            			}else{
            				blurAttr="";
            			}
            			inputTags[a].setAttribute('onblur',blurAttr+'j.blur(this,this.name,this.value);');
		}
    document.getElementById('scheduleSI').getElementsByTagName('tr')[0].parentNode.insertBefore(cloneNode,toInsertBefore);
    
    
    
}catch(e){
        alert('Exception in addSchSIRow method : '+e);
    }
}

//To populate SI values
function populateSI(cgosIncome,simap){
   try{ 
	 
      //111
    document.getElementsByName('scheduleSI.splCodeRateTax[0].splRateInc')[0].value= zeroOrMore(parseInt(cgosIncome.osInc.sec111,10));

    //DTAAOS
    document.getElementsByName('scheduleSI.splCodeRateTax[1].splRateInc')[0].value= zeroOrMore(parseInt(document.getElementsByName('scheduleOS.incChargblSplRateOS.nriIncTaxDtaa.totAmtUnderDtaa')[0].value,10));
    
    //5BB
    document.getElementsByName('scheduleSI.splCodeRateTax[2].splRateInc')[0].value = zeroOrMore(parseInt(cgosIncome.osInc.sec115BB)); 

    //111A
    document.getElementsByName('scheduleSI.splCodeRateTax[3].splRateInc')[0].value= zeroOrMore(parseInt(cgosIncome.osInc.sec115AC_1_a_b,10));
  
    
    deleteSIRow();
    for(var i in simap){
        if(simap[i]!='undefined' && simap[i]!=null && simap[i]!=0){
            var secAdded=checkSectionAddedSI(i,simap[i]);
            if(!secAdded){
            addSchSIRow(i,simap[i]);
          }
        }
       
    }
    for(var si in simap){
      
     simap[si]='';
    }
    calcScheduleSI();
   }catch(e){
       alert('Error in populateSI:' +e);
   }
   
}

//To check Section Added in schedule SI
function checkSectionAddedSI(secCode,secValue){
    try{
    var tab=document.getElementById('scheduleSI');
    var noofRows=tab.rows.length;
    var secAdded=false;
    for(var i=0;i<eval(parseInt(noofRows,10)-3);i++){
       
        if(document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].secCode')[0].value==secCode ){
            document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].splRateInc')[0].value=zeroOrMore(parseInt(secValue,10));
            secAdded=true;
            }
        
    }
    return secAdded;
    }catch(e){
       alert('error in checkSectionAddedSI' +e); 
    }
}

//To delete SI Row
function deleteSIRow(){
    try{
    var siTable=document.getElementById('scheduleSI');
    var noRows=siTable.rows.length;
    if(parseInt(noRows,10) > 6){
    
    for(var i=5;i<parseInt(noRows,10)-1;i++){
       siTable.deleteRow(5); 
    }
    
    }
   
    }catch(e){
        alert('Error in deleteSIRow:'+e);
    }
   }


//To get the Section Text values
function getSectionTextMap(key){
    var sectionTextMap={"1":"111 - Tax on accumulated balance of recognised PF",
                        "5A1ai":"115A(1)(a)(i)- Dividends interest and income from units purchase in foreign currency",
                        "5A1aii":"115A(1)(a)(ii)- Interest received from govt/Indian Concerns recived in Foreign Currency",
                        "5A1aiia":"115A(1) (a)(iia) -Interest from Infrastructure Debt Fund",
                        "5A1aiiaa":"115A(1) (a)(iiaa) -Interest as per Sec. 194LC",
                        "5A1aiiab":"115A(1) (a)(iiab) -Interest as per Sec. 194LD",
                        "5A1aiiac":"115A(1)(a)(iiac) -Interest as per Sec. 194LBA",
                        "5A1aiii":"115A(1) (a)(iii) - Income received in respect of units of UTI purchased in Foreign Currency",
                        "5A1bA":"115A(1)(b)(A)- Income from royalty & technical services",
                        "5A1bB":"115A(1)(b)(B) Income from royalty & technical services",
                        "5AC1ab":"115AC(1)(a & b) - Income from bonds or GDR purchased in foreign currency - non-resident",
                        "5ACA1a":"115ACA(1)(a) - Income from GDR purchased in foreign currency -resident",
                        "5AD1i":"115AD(1)(i) -Income received by an FII in respect of securities (other than units as per Sec 115AB)",
                        "5AD1iP":"115AD(1)(i) -Income received by an FII in respect of bonds or government securities as per Sec 194LD ",
                         "5B":"115B - Profits and gains of life insurance business",
                        "5BB":"115BB (Winnings from lotteries, puzzles, races, games etc.)",
                        "5BBA":"115BBA - Tax on non-residents sportsmen or sports associations",
                        "5BBC":"115BBC - Anonymous donations",
                        "5BBE":"115BBE - Tax on income referred to in sections 68 or 69 or 69A or 69B or 69C or 69D",
                        "5Ea":"115E(a) - Investment income",
                        "DTAAOS":"Chargeable under DTAA rate",
                        "5AD1biip":"115AD(1)(b)(ii)- Short term capital gains referred to in section 111A",
                        "Others":"Others"
    };
    
    return sectionTextMap[key];
}

//To get Section Tax Rate
function getSectionTaxRate(key){
       var sectionRateMap={    		   			
                        "5A1ai":"20",
                        "5A1aii":"20",
                        "5A1aiia":"5",
                        "5A1aiiaa":"5",
                        "5A1aiiab":"5",
                        "5A1aiiac":"5",
                        "5A1aiii":"20",
                        "5A1bA":"25",
                        "5A1bB":"25",
                        "5AC1ab":"10",
                        "5ACA1a":"10",
                        "5AD1i":"20",
                        "5AD1iP":"5",
                        "5B":"12.5",
                        "5BB":"30",
                        "5BBA":"20",
                        "5BBC":"30",
                        "5BBE":"30",
                        "5Ea":"20",
                        "5AD1biip":"15"
    };
    
    return sectionRateMap[key];
    
}

//To populate DTAA values
function populateDTAA(){

    var table=document.getElementById('scheduleTR');
    var noOfRows=table.rows.length;
    var sumSec90=0;
    var sumSec91=0;
      
        for(var i=0;i<eval(parseInt(noOfRows,10)-4);i++){
	        if(document.getElementsByName('scheduleTR1.scheduleTR['+i+'].relavantArticleDTAA')[0].value=='91'){
	        	sumSec91=eval(sumSec91+ parseInt(coalesce(document.getElementsByName('scheduleTR1.scheduleTR['+i+'].taxReliefOutsideIndia')[0].value),10));
	        
	        } else if(document.getElementsByName('scheduleTR1.scheduleTR['+i+'].relavantArticleDTAA')[0].value=='90' ||
		        document.getElementsByName('scheduleTR1.scheduleTR['+i+'].relavantArticleDTAA')[0].value=='90A'){
		        sumSec90=eval(sumSec90+parseInt(coalesce(document.getElementsByName('scheduleTR1.scheduleTR['+i+'].taxReliefOutsideIndia')[0].value),10));
	        }
        
        }
        
        document.getElementsByName('scheduleTR1.totalIncomeOutIndia')[0].value=sumSec90;
        document.getElementsByName('scheduleTR1.totalIncomeOutIndiaDTAA')[0].value=sumSec91;
        

}

function adjustTDS2(){
	var tab = document.getElementById('scheduleTDS2');
	var inputs = tab.getElementsByTagName('INPUT');
	var portCode = document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].value;
	for(var i=0;i<inputs.length;i++){
		if(inputs[i].name.match('claimSpouseHands$')){
			if(portCode=='Y'){
				inputs[i].disabled = false;
			}else{
				inputs[i].disabled = true;
				inputs[i].value = '';
			}
		}
	}
}




function checkEmptyAmtSpouse(){
var tab = document.getElementById('scheduleTDS2');
var allInputTags = tab.getElementsByTagName('INPUT');

var portuVal = document.getElementsByName('partAGEN1.filingStatus.portugeseCC5A')[0].value;
var isRowBlank = checkRowBlank('scheduleTDS2', 3, 2);
if(portuVal=='Y' && isRowBlank == false){
			for(var i = 0; i < allInputTags.length; i++) {
				if (allInputTags[i].name.match("claimSpouseHands$")) {
						if(allInputTags[i].value==''){
							addError(allInputTags[i],' Amount claimed in the hands  of spouse is mandatory as the assessee is governed by Portuguese Civil Code under Sec 5A. In case of nil amount, please enter zero',true);
							j.setFieldError(allInputTags[i].name,'Amount claimed in the hands  of spouse is mandatory as the assessee is governed by Portuguese Civil Code under Sec 5A. In case of nil amount, please enter zero');
						}
					}
				}
		}      
}

function validateSec50C_CG(capGainType) {
	var fullConsideration = document.getElementsByName('scheduleCGPost45.'+capGainType+'.saleofLandBuild.fullConsideration')[0];
	var propertyValuation = document.getElementsByName('scheduleCGPost45.'+capGainType+'.saleofLandBuild.propertyValuation')[0];
	var fullConsideration50C = document.getElementsByName('scheduleCGPost45.'+capGainType+'.saleofLandBuild.fullConsideration50C')[0];
	
	if(fullConsideration50C.value!=fullConsideration.value && fullConsideration50C.value!=propertyValuation.value){
		j.setFieldError('scheduleCGPost45.'+capGainType+'.saleofLandBuild.fullConsideration50C','Please enter value from ai or aii only');
		addErrorXHTML(fullConsideration50C ,'Please enter value from ai or aii only',true);
	}
}

function sumSectionWise(tableId, arr){
		var tab = document.getElementById(tableId);
		var selects = tab.getElementsByTagName("SELECT");
		for(var i=0;i<selects.length;i++){
			if((selects[i].name.match('section$') || selects[i].name.match('deductedSecCode$')) && selects[i].value!=''){
				var name = selects[i].name;
				var str1 = name.substr(0,name.lastIndexOf('[')+1);
				var amt = document.getElementsByName(str1+i+'].amount')[0];
				if(tableId=='schduleCGDed'){
					amt = document.getElementsByName(str1+i+'].amtDed')[0];
				}
				arr[selects[i].value] = parseInt(arr[selects[i].value]) + parseInt(coalesce(amt.value));
			}
		}
		return arr;
}

//To validate sch CG Section wise Deduction
function validateCGSecwiseDed(){
	var arr = {'54':0,'54B':0,'54EC':0,'54F':0,'54GB':0,'115F':0};
	var arrDed = {'54':0,'54B':0,'54EC':0,'54F':0,'54GB':0,'115F':0};
	sumSectionWise('ltcgDeduction1', arr);
	sumSectionWise('ltcgDeduction2', arr);
	sumSectionWise('scheduleCGltcg7', arr);
	sumSectionWise('scheduleCGltcg4_ded1', arr);
	
	
	arr['54B'] = parseInt(arr['54B']) + coalesceSetRet('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.exemptionOrDednUs54');
	arr['115F'] = parseInt(arr['115F']) + coalesceSetRet('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.dednSpecAssetus115');
	arr['115F'] = parseInt(arr['115F']) + coalesceSetRet('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.dednOtherSpecAssetus115');
	
	var len = document.getElementById('scheduleCGltcg3').tBodies.length;
	for(var i=0;i<len;i++){
		sumSectionWise('scheduleCGltcg3_ded'+(i+1), arr);
	}
	len = document.getElementById('stcg10pctTab').tBodies.length;
	for(var i=0;i<len;i++){
		sumSectionWise('stcg10pctTab_ded'+(i+1), arr);
	}	

	sumSectionWise('schduleCGDed', arrDed);
	
	alert(arr['54']+ ','+arr['54B']+ ','+arr['54EC']+ ','+arr['54F']+ ','+arr['54GB']+ ','+arr['115F']);
	alert(arrDed['54']+ ','+arrDed['54B']+ ','+arrDed['54EC']+ ','+arrDed['54F']+ ','+arrDed['54GB']+ ','+arrDed['115F']);
	
	if(arr['54']!=arrDed['54']){
		j.setFieldError('scheduleCGPost45.deducClaimInfo.deducClaimDtls[0].deductedSecCode','Deduction under 54 must match with deduction in table D');
		addErrorXHTML('','Deduction under 54 must match with deduction in table D',true);		
	}
	if(arr['54B']!=arrDed['54B']){
		j.setFieldError('scheduleCGPost45.deducClaimInfo.deducClaimDtls[0].deductedSecCode','Deduction under 54B must match with deduction in table D');
		addErrorXHTML('','Deduction under 54B must match with deduction in table D',true);		
	}
	if(arr['54EC']!=arrDed['54EC']){
		j.setFieldError('scheduleCGPost45.deducClaimInfo.deducClaimDtls[0].deductedSecCode','Deduction under 54EC must match with deduction in table D');
		addErrorXHTML('','Deduction under 54EC must match with deduction in table D',true);		
	}
	if(arr['54F']!=arrDed['54F']){
		j.setFieldError('scheduleCGPost45.deducClaimInfo.deducClaimDtls[0].deductedSecCode','Deduction under 54F must match with deduction in table D');
		addErrorXHTML('','Deduction under 54F must match with deduction in table D',true);		
	}
	if(arr['54GB']!=arrDed['54GB']){
		j.setFieldError('scheduleCGPost45.deducClaimInfo.deducClaimDtls[0].deductedSecCode','Deduction under 54GB must match with deduction in table D');
		addErrorXHTML('','Deduction under 54GB must match with deduction in table D',true);		
	}	
	if(arr['115F']!=arrDed['115F']){
		j.setFieldError('scheduleCGPost45.deducClaimInfo.deducClaimDtls[0].deductedSecCode','Deduction under 115F must match with deduction in table D');
		addErrorXHTML('','Deduction under 115F must match with deduction in table D',true);		
	}		
}


//To Check HP Share Property
function CheckHPShareProperty(){
	var totHp=eval(parseInt(document.getElementById('scheduleHPLast').cells[0].textContent)-1);
		
	for(var i=0;i<totHp;i++){
		
		if(document.getElementsByName('scheduleHP.propertyDetails['+i+'].propCoOwnedFlg')[0].value=='YES') {
			var count = i;
			var AssessPerc = document.getElementsByName('scheduleHP.propertyDetails['+i+'].asseseeShareProperty')[0];
			var tab = document.getElementById('scheduleHP'+(++count));
		
			var sumOfCoOwner = parseFloat('0');
			
			var rowCount = tab.rows.length;
			
			for(var k=0;k<rowCount-2;k++) {
				
				sumOfCoOwner = sumOfCoOwner + (mulFloatBy100(document.getElementsByName('scheduleHP.propertyDetails['+i+'].coOwners['+k+'].percentShareProperty')[0].value));
			}
			
			if(checkHPShareSum((parseInt(sumOfCoOwner)+mulFloatBy100(AssessPerc.value))/100)){
				addErrorXHTML(AssessPerc,'Sum of Assessee Percentage and Co-owner(s) Percentage should be equal to 100 percent',true);
				j.setFieldError('scheduleHP.propertyDetails['+i+'].asseseeShareProperty','Sum of Assessee Percentage and Co-owner(s) Percentage should be equal to 100 percent');
			}
		}
	}
}

function checkHPShareSum(total) {
	if(total>=99.9 && total<=100) {
		return false;
	}
	return true;
}

function scheduleFSIAlert()
{
   var tableFSI = checkRowBlank('scheduleFSI', 8, 2);
   if(tableFSI==false){
   
   addErrorXHTML('','Please ensure that the incomes shown in Schedule FSI  are also reflected under respective income schedules.');
  
  }

}

function partBttiSec89Alert()
{
   var sec89 = document.getElementsByName('partBTTI.computationOfTaxLiability.taxRelief.section89')[0].value;
   alert("coming ");

   if(sec89 != 0 ){
	   alert("getting error");
	   addErrorXHTML('','Please ensure to submit Form 10E.');
  }

}

function alertItr2User()
{
	var incSal = document.getElementsByName('partBTI.salaries')[0].value;
	var tab1 = document.getElementById('scheduleTDS1');
    var noOfRows=tab1.rows.length;
	var sum = 0;
	var amt = 0;
		
	for ( var i = 0; i < (noOfRows-3); i++) {
		amt = document.getElementsByName('scheduleTDS1.tdSonOthThanSal['+i+'].incChrgSal')[0].value;
		sum = eval(parseInt(sum,10) + parseInt(coalesce(amt),10));
	}
 
	var tdsSalminusTenPer = sum*parseFloat('0.90');
	var errText="";
	var i=1;
	var amountPayable = document.getElementsByName('partBTTI.taxPaid.balTaxPayable')[0].value;
	var fileSec = document.getElementsByName('partAGEN1.filingStatus.returnFileSec')[0].value;

	if(incSal < tdsSalminusTenPer) {
		errText+=(i++)+". The amount of salary disclosed in \"Income details/Part BTI\" is less than 90% of Salary reported in TDS1.\n\n";
	}
	if(fileSec=='20') {
		errText+=(i++)+'. To file return u/s 119(2)(b), post login in e-Filing portal, go to "e-File" --> "Income Tax Return" and select the applicable AY, ITR and other options.\n\n';
	}
	if(amountPayable>0) {
		errText+=(i++)+". Please ensure that the taxes are paid before the submission of the return, else return shall be treated as defective.\n";
	}
		main.generateMsgDialogWithOk(errText,"");

}


//To check Schedule 5A
function checkSchedule5A(){
var hpIncome1 = document.getElementsByName('schedule5A2014.hPHeadIncome.incRecvdUndHead')[0].value;
var busHeadIncome1 = document.getElementsByName('schedule5A2014.hPHeadIncome.amtApprndOfSpouse')[0].value;
if(parseInt(busHeadIncome1,10) > parseInt(hpIncome1,10)){
	j.setFieldError('schedule5A2014.hPHeadIncome.amtApprndOfSpouse','Amount apportioned in the hands of the spouse in House Property cannot exceed Income received under the head');
		addErrorXHTML('','Amount apportioned in the hands of the spouse in House Property cannot exceed Income received under the head',true);	
}

var hpIncome2 = document.getElementsByName('schedule5A2014.hPHeadIncome.amtTDSDeducted')[0].value;
var busHeadIncome2 = document.getElementsByName('schedule5A2014.hPHeadIncome.tDSApprndOfSpouse')[0].value;
if(parseInt(busHeadIncome2,10) > parseInt(hpIncome2,10)){
	j.setFieldError('schedule5A2014.hPHeadIncome.tDSApprndOfSpouse','TDS apportioned in the hands of spouse in House Property cannot exceed Amount of TDS deducted on income at (ii)');
		addErrorXHTML('','TDS apportioned in the hands of spouse in House Property cannot exceed Amount of TDS deducted on income at (ii)',true);	
}

var hpIncome3 = document.getElementsByName('schedule5A2014.busHeadIncome.incRecvdUndHead')[0].value;
var busHeadIncome3 = document.getElementsByName('schedule5A2014.busHeadIncome.amtApprndOfSpouse')[0].value;
if(parseInt(busHeadIncome3,10) > parseInt(hpIncome3,10)){
	j.setFieldError('schedule5A2014.busHeadIncome.amtApprndOfSpouse','Amount apportioned in the hands of the spouse in Business/Profession cannot exceed Income received under the head');
		addErrorXHTML('','Amount apportioned in the hands of the spouse in Business/Profession cannot exceed Income received under the head',true);	
}

var hpIncome4 = document.getElementsByName('schedule5A2014.busHeadIncome.amtTDSDeducted')[0].value;
var busHeadIncome4 = document.getElementsByName('schedule5A2014.busHeadIncome.tDSApprndOfSpouse')[0].value;
if(parseInt(busHeadIncome4,10) > parseInt(hpIncome4,10)){
	j.setFieldError('schedule5A2014.busHeadIncome.tDSApprndOfSpouse','TDS apportioned in the hands of spouse in Business/Profession cannot exceed Amount of TDS deducted on income at (ii)');
		addErrorXHTML('','TDS apportioned in the hands of spouse in Business/Profession cannot exceed Amount of TDS deducted on income at (ii)',true);	
}

var hpIncome5 = document.getElementsByName('schedule5A2014.capGainHeadIncome.incRecvdUndHead')[0].value;
var busHeadIncome5 = document.getElementsByName('schedule5A2014.capGainHeadIncome.amtApprndOfSpouse')[0].value;
if(parseInt(busHeadIncome5,10) > parseInt(hpIncome5,10)){
	j.setFieldError('schedule5A2014.capGainHeadIncome.amtApprndOfSpouse','Amount apportioned in the hands of the spouse in Capital Gains cannot exceed Income received under the head');
		addErrorXHTML('','Amount apportioned in the hands of the spouse in Capital Gains cannot exceed Income received under the head',true);	
}

var hpIncome6 = document.getElementsByName('schedule5A2014.capGainHeadIncome.amtTDSDeducted')[0].value;
var busHeadIncome6 = document.getElementsByName('schedule5A2014.capGainHeadIncome.tDSApprndOfSpouse')[0].value;
if(parseInt(busHeadIncome6,10) > parseInt(hpIncome6,10)){
	j.setFieldError('schedule5A2014.capGainHeadIncome.tDSApprndOfSpouse','TDS apportioned in the hands of spouse in Capital Gains cannot exceed Amount of TDS deducted on income at (ii)');
		addErrorXHTML('','TDS apportioned in the hands of spouse in Capital Gains cannot exceed Amount of TDS deducted on income at (ii)',true);	
}

var hpIncome7 = document.getElementsByName('schedule5A2014.otherSourcesHeadIncome.incRecvdUndHead')[0].value;
var busHeadIncome7 = document.getElementsByName('schedule5A2014.otherSourcesHeadIncome.amtApprndOfSpouse')[0].value;
if(parseInt(busHeadIncome7,10) > parseInt(hpIncome7,10)){
	j.setFieldError('schedule5A2014.otherSourcesHeadIncome.amtApprndOfSpouse','Amount apportioned in the hands of the spouse in Other sources cannot exceed Income received under the head');
		addErrorXHTML('','Amount apportioned in the hands of the spouse in Other sources cannot exceed Income received under the head',true);	
}

var hpIncome8 = document.getElementsByName('schedule5A2014.otherSourcesHeadIncome.amtTDSDeducted')[0].value;
var busHeadIncome8 = document.getElementsByName('schedule5A2014.otherSourcesHeadIncome.tDSApprndOfSpouse')[0].value;
if(parseInt(busHeadIncome8,10) > parseInt(hpIncome8,10)){
	j.setFieldError('schedule5A2014.otherSourcesHeadIncome.tDSApprndOfSpouse','TDS apportioned in the hands of spouse in Other sources cannot exceed Amount of TDS deducted on income at (ii)');
		addErrorXHTML('','TDS apportioned in the hands of spouse in Other sources cannot exceed Amount of TDS deducted on income at (ii)',true);	
}

var hpIncome9 = document.getElementsByName('schedule5A2014.hPHeadIncome.incRecvdUndHead')[0].value;
var busHeadIncome9 = document.getElementsByName('schedule5A2014.hPHeadIncome.amtTDSDeducted')[0].value;
if(parseInt(busHeadIncome9,10) > parseInt(hpIncome9,10)){
	j.setFieldError('schedule5A2014.hPHeadIncome.amtTDSDeducted','Amount of TDS deducted on income at (ii) should not exceed Income received under the head');
	addErrorXHTML('','Amount of TDS deducted on income at (ii) should not exceed Income received under the head',true);	
}

var hpIncome10 = document.getElementsByName('schedule5A2014.capGainHeadIncome.incRecvdUndHead')[0].value;
var busHeadIncome10 = document.getElementsByName('schedule5A2014.capGainHeadIncome.amtTDSDeducted')[0].value;
if(parseInt(busHeadIncome10,10) > parseInt(hpIncome10,10)){
	j.setFieldError('schedule5A2014.capGainHeadIncome.amtTDSDeducted','Amount of TDS deducted on income at (ii) should not exceed Income received under the head');
	addErrorXHTML('','Amount of TDS deducted on income at (ii) should not exceed Income received under the head',true);	
}

var hpIncome11 = document.getElementsByName('schedule5A2014.otherSourcesHeadIncome.incRecvdUndHead')[0].value;
var busHeadIncome11 = document.getElementsByName('schedule5A2014.otherSourcesHeadIncome.amtTDSDeducted')[0].value;
if(parseInt(busHeadIncome11,10) > parseInt(hpIncome11,10)){
	j.setFieldError('schedule5A2014.otherSourcesHeadIncome.amtTDSDeducted','Amount of TDS deducted on income at (ii) should not exceed Income received under the head');
	addErrorXHTML('','Amount of TDS deducted on income at (ii) should not exceed Income received under the head',true);	
}
}


function enableScheduleOSOther(){
var tabl = document.getElementById('schduleOsf');
	var allSelects = tabl.getElementsByTagName('SELECT'); 
	for(var i = 0; i < allSelects.length; i++) {	
			var name = allSelects[i].name;
			var index = name.substring(name.indexOf('[')+1, name.indexOf(']'));
			if(allSelects[i].value=='Others'){
				document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].otherDesc')[0].style.display='';
			} else {
				document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].otherDesc')[0].style.display='none';
				document.getElementsByName('scheduleOS.incOthThanOwnRaceHorse.othersGrossDtls['+ index +'].otherDesc')[0].value='';
			}
	}
}

//To calculate Net Agriculture Income for EI
function calculateNetAgricultureIncomeforEI(){
	
	var grossAgriReceipt7B8 = document.getElementsByName('scheduleEI.grossAgriReceipt7B8')[0].value;
	var expendAgriculture = document.getElementsByName('scheduleEI.expendAgriculture')[0].value;
	var expendAgricultureUnabsorbed = document.getElementsByName('scheduleEI.expendAgricultureUnabsorbed')[0].value;
	
	var result = zeroOrMore(zeroOrMore(grossAgriReceipt7B8) - zeroOrMore(expendAgriculture) - zeroOrMore(expendAgricultureUnabsorbed));
	document.getElementsByName('scheduleEI.netAgriIncOrOthrIncRule7')[0].value = result;
}

function enableTable(element, value, tableId){

	var flag =document.getElementsByName(element)[0].value;
	var tabId = "#"+tableId;
		
	$(tabId).find(':input').prop('disabled', true);
	$(tabId).find('.addbtn').prop('hidden', true);
	
	if(flag==value){
			$(tabId).find('.addbtn').prop('hidden', false);
			$(tabId).find(':input').prop('disabled', false);
		}else{
			$(tabId).find('[type=\"checkbox\"]').attr('checked','checked');
			if(tableId == 'scheduleLtcgunUtilizedCapGain54' || tableId == 'scheduleStcgunUtilizedCapGain54') {
				deleteRowTable(tableId,2,2);
			} else {
				deleteRowTable(tableId,2,1);
			}
			$(tabId).find(':input').prop('disabled', true);
			$(tabId).find('.addbtn').prop('hidden', true);
		}
}

//to enable Table For NRI
function enableTableForNRI(element, value, tableId){

	var flag =document.getElementsByName(element)[0].value;
	var tabId = "#"+tableId;
		
	$(tabId).find(':input').prop('disabled', true);
	$(tabId).find('.addbtn').prop('hidden', true);
	
	if(flag==value){
			$(tabId).find('.addbtn').prop('hidden', false);
			$(tabId).find(':input').prop('disabled', false);
		}else{
			$(tabId).find('[type=\"checkbox\"]').attr('checked','checked');
			deleteRowTable(tableId,1,1);
			$(tabId).find(':input').prop('disabled', true);
			$(tabId).find('.addbtn').prop('hidden', true);
		}
}

//To calculate Pure SI Tax
function panValidation80G(tableId) {

	var pan = document.getElementsByName('partAGEN1.personalInfo.pan')[0].value;
	var verificationPAN = document.getElementsByName('verification.declaration.assesseeVerPAN')[0].value;
	var table = document.getElementById(tableId);
	var allInputTags = table.getElementsByTagName('input');
	for(var i = 0; i < allInputTags.length; i++) {
		if (allInputTags[i].name.match("doneePanNo$")) {
			if(allInputTags[i].value != '' && (allInputTags[i].value == pan || allInputTags[i].value == verificationPAN )){
				j.setFieldError(allInputTags[i].name,'Enter the PAN of the person to whom the donation is made.');
			}
		}
	}
}

//To calculate Pure SI Tax
function calculatePureSITax(){
	
	var rowCount1=countRowInTable('scheduleSI.splCodeRateTax','splRateInc');
	var sum = 0;
	var sumWithDtaa = 0;
	var dtaa = document.getElementsByName('scheduleSI.splCodeRateTax[1].splRateIncTax')[0].value;
	for(var i = 0; i < rowCount1; i++) {

		var section = document.getElementsByName('scheduleSI.splCodeRateTax[' + i +'].secCode')[0].value;
		
		if(section=='1A'||section=='21'||section=='22'||section=='21ciii'||section=='5AC1c'||section=='5ACA1b'||section=='5ADii'||section=='5ADiii'||section=='5Eacg'||section=='5AD1biip'){
			sum = parseInt(sum) + parseInt(document.getElementsByName('scheduleSI.splCodeRateTax['+i+'].splRateIncTax')[0].value); 
		}
			
	}
	sumWithDtaa = sum;
	return parseInt(sumWithDtaa);
	
}

//To check No Of Rows Filled
function checkNoOfRowsFilled(){
	
	var tab = document.getElementById('scheduleBA');
	var rowCount = tab.rows.length;
	var count =  parseInt(0,10);
	var noOfBankAccounts = document.getElementsByName('partBTTI.bankAccountDtls.noOfBankAcc')[0].value;
	for ( var i = 0; i < (rowCount-2); i++) {
		var IFSC = document.getElementsByName('partBTTI.bankAccountDtls.otherBankDetails['+i+'].ifscCode')[0].value;
		if(IFSC !=""){
			count = count+1;
		}
	}
	if(noOfBankAccounts != '' && (noOfBankAccounts-1) != count){
		 j.setFieldError('partBTTI.bankAccountDtls.noOfBankAcc','Number of bank accounts held during the pervious year should be equal to number of rows entered in the below tables');
	}
	
}


//To set Values CG 54B
function setValuesCG54B() {

	var yearConstant = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54B.yearConst')[0].value;
	var amountUtilized = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54B.amountUtilized')[0].value;
	var amountUnUtilized = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54B.amountUnUtilized')[0].value;

	if (yearConstant == "" && amountUtilized == "" && amountUnUtilized == "") {
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54B.section')[0].value = '';
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54B.year')[0].value = '';
	} else {
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54B.section')[0].value = '54B';
		document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54B.year')[0].value = '2012-13';
	}

	var tab = document.getElementById('scheduleLtcgunUtilizedCapGain54');
	var rowCount = tab.rows.length - 4;
	for ( var k = 0; k < rowCount; k++) {
		var section = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54['+ k + '].section')[0].value;
		var yearConst = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54['+ k + '].yearConst')[0].value;
		var amountUtilized = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54['+ k + '].amountUtilized')[0].value;
		var amountUnUtilized = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54['+ k + '].amountUnUtilized')[0].value;
		var ay = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.unUtilizedCapGain54['+ k + '].ay')[0];
		if (section == "" && yearConst == "" && amountUtilized == "" && amountUnUtilized == "") {
			ay.value = '';
		} else {
			ay.value = '2011-12';
		}
	}
	
	var yearConstantStcg = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54B.yearConst')[0].value;
	var amountUtilizedStcg = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54B.amountUtilized')[0].value;
	var amountUnUtilizedStcg = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54B.amountUnUtilized')[0].value;

	if (yearConstantStcg == "" && amountUtilizedStcg == "" && amountUnUtilizedStcg == "") {
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54B.section')[0].value = '';
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54B.year')[0].value = '';
	} else {
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54B.section')[0].value = '54B';
		document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54B.year')[0].value = '2012-13';
	}

	var tab1 = document.getElementById('scheduleStcgunUtilizedCapGain54');
	var rowCount1 = tab1.rows.length - 4;
	for ( var k = 0; k < rowCount1; k++) {
		var section = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54['+ k + '].section')[0].value;
		var yearConst = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54['+ k + '].yearConst')[0].value;
		var amountUtilized = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54['+ k + '].amountUtilized')[0].value;
		var amountUnUtilized = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54['+ k + '].amountUnUtilized')[0].value;
		var ay = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54['+ k + '].ay')[0];
		if (section == "" && yearConst == "" && amountUtilized == "" && amountUnUtilized == "") {
			ay.value = '';
		} else {
			ay.value = '2011-12';
		}
	}
}

//To validate LTCG Section Wise DTAA
function validateLTCGSectionWiseDTAA() {
	var arr = {'B1e':0,'B2e':0,'B3e_22':0,'B3e_5ACA1b':0,'B4c':0,'B5e_21ciii':0,'B5e_5AC1c':0,'B5e_5ADiii':0,'B6c':0,'B6f':0,'B7e':0,'B8':0};
	var tab = document.getElementById('scheduleLtcgDtaa');
	  var rowCount = tab.rows.length -2;
	  for(var i=0; i<rowCount; i++) {
	    var itemIncluded = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.ltcgUnderDtaa['+ i +'].itemIncluded')[0].value;
	    var amount = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.ltcgUnderDtaa['+ i +'].amount')[0].value;  
	   if(itemIncluded == 'B1e') {
	       arr['B1e'] = parseInt(arr['B1e'],10) +  parseInt(coalesce(amount),10);
	    } else if(itemIncluded == 'B2e') {
		       arr['B2e'] = parseInt(arr['B2e'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'B3e_22') {
		       arr['B3e_22'] = parseInt(arr['B3e_22'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'B3e_5ACA1b') {
		       arr['B3e_5ACA1b'] = parseInt(arr['B3e_5ACA1b'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'B4c') {
		       arr['B4c'] = parseInt(arr['B4c'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'B5e_21ciii') {
		       arr['B5e_21ciii'] = parseInt(arr['B5e_21ciii'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'B5e_5AC1c') {
			   arr['B5e_5AC1c'] = parseInt(arr['B5e_5AC1c'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'B5e_5ADiii') {
		       arr['B5e_5ADiii'] = parseInt(arr['B5e_5ADiii'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'B6c') {
		       arr['B6c'] = parseInt(arr['B6c'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'B6f') {
		       arr['B6f'] = parseInt(arr['B6f'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'B7e') {
		       arr['B7e'] = parseInt(arr['B7e'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'B8') {
		       arr['B8'] = parseInt(arr['B8'],10) +  parseInt(coalesce(amount),10);
		}
	  }
	
	var table = document.getElementById('scheduleLtcgDtaa');
	var rowCount = table.rows.length -2;
	
	var dtaaSection = [];
	
	for(var i=0; i<rowCount; i++) {
		var itemIncluded = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.ltcgUnderDtaa['+ i +'].itemIncluded')[0].value;
		if(itemIncluded != '' && dtaaSection.indexOf(itemIncluded) == -1) {
			dtaaSection.push(itemIncluded);
		}
	}
	
	var fullConsideration50C = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.fullConsideration50C')[0];
	if(dtaaSection.indexOf('B1e') != -1 && arr['B1e'] > 0 && fullConsideration50C.value == 0) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.fullConsideration50C','B1e value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(fullConsideration50C,'B1e value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	var fullConsideration = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofBondsDebntr.fullConsideration')[0];
	if(dtaaSection.indexOf('B2e') != -1 && arr['B2e'] > 0  && fullConsideration.value == 0) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.saleofBondsDebntr.fullConsideration','B2e value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(fullConsideration,'B2e value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	var table1 = document.getElementById('scheduleCGltcg3');
	var rowCount1 = table1.rows.length/11;
	  
	var arrSection = [];
	var arrAmount = {'22':0,'5ACA1b':0};
	
	for(var k=0; k<rowCount1; k++) {
	 var sectionCode = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable['+k+'].sectionCode')[0].value;
	 var fullConsideration = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable['+k+'].fullConsideration')[0].value;
		  if(sectionCode != '' && arrSection.indexOf(sectionCode) == -1) {
			  arrSection.push(sectionCode);
			  arrAmount[sectionCode] = fullConsideration;
			}
	 }
	
	if(dtaaSection.indexOf('B3e_22') != -1 && arr['B3e_22'] > 0 && (arrSection.indexOf('22') == -1 || arrAmount['22'] == 0)) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode','22 section code should select in B3 as there is an entry in DTAA table.');
		addErrorXHTML(document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode')[0],'22 section code should select in B3 as there is an entry in DTAA table.',true);
	}
	if(dtaaSection.indexOf('B3e_5ACA1b') != -1 && arr['B3e_5ACA1b'] > 0 && (arrSection.indexOf('5ACA1b') == -1 || arrAmount['5ACA1b'] == 0)) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode','5ACA1b section should select in B3 as there is an entry in DTAA table.');
		addErrorXHTML(document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode')[0],'5ACA1b section should select in B3 as there is an entry in DTAA table.',true);
	}
	
	var BalanceCG = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.BalanceCG')[0];
	if(dtaaSection.indexOf('B4c') != -1 && arr['B4c'] > 0 && BalanceCG.value == 0) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.BalanceCG','B4c value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(BalanceCG,'B4c value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	
	var table2 = document.getElementById('stcg10pctTab');
	var rowCount2 = table2.rows.length/11;
	  
	var arrSection1 = [];
	var arrAmount1 = {'21ciii':0,'5AC1c':0,'5ADiii':0};
	
	for(var a=0; a<rowCount2; a++) {
	 var sectionCode = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115['+a+'].sectionCode')[0].value;
	 var amount = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115['+a+'].fullConsideration')[0].value;
		  if(sectionCode != '' && arrSection1.indexOf(sectionCode) == -1) {
			  arrSection1.push(sectionCode);
			  arrAmount1[sectionCode] = amount;
			}
	 }
	
	if(dtaaSection.indexOf('B5e_21ciii') != -1 && arr['B5e_21ciii'] > 0 && (arrSection1.indexOf('21ciii') == -1 || arrAmount1['21ciii'] == 0)) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode','21ciii section code should select in B5 as there is an entry in DTAA table.');
		addErrorXHTML(document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode')[0],'21ciii section code should select in B5 as there is an entry in DTAA table.',true);
	}
	
	if(dtaaSection.indexOf('B5e_5AC1c') != -1 && arr['B5e_5AC1c'] > 0 && (arrSection1.indexOf('5AC1c') == -1 || arrAmount1['5AC1c'] == 0)) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode','5AC1c section code should select in B5 as there is an entry in DTAA table.');
		addErrorXHTML(document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode')[0],'5AC1c section code should select in B5 as there is an entry in DTAA table.',true);
	}
	
	if(dtaaSection.indexOf('B5e_5ADiii') != -1 && arr['B5e_5ADiii'] > 0 && (arrSection1.indexOf('5ADiii') == -1 || arrAmount1['5ADiii'] == 0)) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode','5ADiii section code should select in B5 as there is an entry in DTAA table.');
		addErrorXHTML(document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].sectionCode')[0],'5ADiii section code should select in B5 as there is an entry in DTAA table.',true);
	}
	
	var balonSpeciAsset = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.balonSpeciAsset')[0];
	if(dtaaSection.indexOf('B6c') != -1 && arr['B6c'] > 0 && balonSpeciAsset.value == 0) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.balonSpeciAsset','B6c value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(balonSpeciAsset,'B6c value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	var balOtherthanSpecAsset = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.balOtherthanSpecAsset')[0];
	if(dtaaSection.indexOf('B6f') != -1 && arr['B6f'] > 0 && balOtherthanSpecAsset.value == 0) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.balOtherthanSpecAsset','B6f value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(balOtherthanSpecAsset,'B6f value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	var fullConsiderationB7e = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofAssetNA.deductSec48.fullConsideration')[0];
	if(dtaaSection.indexOf('B7e') != -1 && arr['B7e'] > 0  && fullConsiderationB7e.value == 0) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.saleofAssetNA.deductSec48.fullConsideration','B7e value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(fullConsiderationB7e,'B7e value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	var totAmtStcgUnderDtaa = document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.stcgUnderDtaa.totAmtStcgUnderDtaa')[0];
	if(dtaaSection.indexOf('B8') != -1 && arr['B8'] > 0 && totAmtStcgUnderDtaa.value == 0) {
		j.setFieldError('scheduleCGPost45.longTermCapGainPost45.stcgUnderDtaa.totAmtStcgUnderDtaa','B8 value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(totAmtStcgUnderDtaa,'B8 value should not be zero as there is an entry in DTAA table.',true);	
	}
}

//To validate STCG Section Wise DTAA
function validateSTCGSectionWiseDTAA() {
	var arr = {'A1e':0,'A2e_111A':0,'A2e_115AD':0,'A3a':0,'A3b':0,'A4e':0,'A5e':0,'A6':0};
	var tab = document.getElementById('scheduleStcgDtaa');
	  var rowCount = tab.rows.length -2;
	  for(var i=0; i<rowCount; i++) {
	    var itemIncluded = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.stcgUnderDtaa['+ i +'].itemIncluded')[0].value;
	    var amount = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.stcgUnderDtaa['+ i +'].amount')[0].value;  
	   if(itemIncluded == 'A1e') {
	       arr['A1e'] = parseInt(arr['A1e'],10) +  parseInt(coalesce(amount),10);
	    } else if(itemIncluded == 'A3a') {
		       arr['A3a'] = parseInt(arr['A3a'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'A3b') {
		       arr['A3b'] = parseInt(arr['A3b'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'A4e') {
		       arr['A4e'] = parseInt(arr['A4e'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'A5e') {
		       arr['A5e'] = parseInt(arr['A5e'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'A6') {
		       arr['A6'] = parseInt(arr['A6'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'A2e_111A') {
			   arr['A2e_111A'] = parseInt(arr['A2e_111A'],10) +  parseInt(coalesce(amount),10);
		} else if(itemIncluded == 'A2e_115AD') {
		       arr['A2e_115AD'] = parseInt(arr['A2e_115AD'],10) +  parseInt(coalesce(amount),10);
		}
	  }
	
	var table = document.getElementById('scheduleStcgDtaa');
	var rowCount = table.rows.length -2;
	
	var dtaaSection = [];
	
	for(var i=0; i<rowCount; i++) {
		var itemIncluded = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.stcgUnderDtaa['+ i +'].itemIncluded')[0].value;
		if(itemIncluded != '' && dtaaSection.indexOf(itemIncluded) == -1) {
			dtaaSection.push(itemIncluded);
		}
	}
	
	var table1 = document.getElementById('scheduleCGstcg2');
	var rowCount1 = table1.rows.length/10;
	  
	var arrSection2 = [];
	var arrAmount2 = {'1A':0,'5AD1biip':0};
	
	for(var k=0; k<rowCount1; k++) {
	 var section = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT['+ k +'].section')[0].value;
	 var amount = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT['+ k +'].fullConsideration')[0].value;
		  if(section != '' && arrSection2.indexOf(section) == -1) {
			  arrSection2.push(section);
			  arrAmount2[section] = amount;
			}
	 }
	
	var fullConsideration50C = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.fullConsideration50C')[0];
	if(dtaaSection.indexOf('A1e') != -1 && arr['A1e'] > 0 && fullConsideration50C.value == 0) {
		j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.fullConsideration50C','A1e value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(fullConsideration50C,'A1e value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	
	if(dtaaSection.indexOf('A2e_111A') != -1 && arr['A2e_111A'] > 0 && (arrSection2.indexOf('1A') == -1 || arrAmount2['1A'] == 0)) {
		j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT[0].section','111A section should select in A2 as there is an entry in DTAA table.');
		addErrorXHTML(document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT[0].section')[0],'111A section should select in A2 as there is an entry in DTAA table.',true);
	}
	
	if(dtaaSection.indexOf('A2e_115AD') != -1 && arr['A2e_115AD'] > 0 && (arrSection2.indexOf('5AD1biip') == -1 || arrAmount2['5AD1biip'] == 0)) {
		j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT[0].section','115AD(1)(b)(ii) section should select in A2 as there is an entry in DTAA table.');
		addErrorXHTML(document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT[0].section')[0],'115AD(1)(b)(ii) section should select in A2 as there is an entry in DTAA table.',true);	
	}
	
	var nRItaxSTTPaid = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTPaid')[0];
	if(dtaaSection.indexOf('A3a') != -1 && arr['A3a'] > 0 && nRItaxSTTPaid.value == 0) {
		j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTPaid','A3a value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(nRItaxSTTPaid,'A3a value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	var nRItaxSTTNotPaid = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTNotPaid')[0];
	if(dtaaSection.indexOf('A3b') != -1 && arr['A3b'] > 0 && nRItaxSTTNotPaid.value == 0) {
		j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTNotPaid','A3b value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(nRItaxSTTNotPaid,'A3b value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	var fullConsideration = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.fullConsideration')[0];
	if(dtaaSection.indexOf('A4e') != -1 && arr['A4e'] > 0 && fullConsideration.value == 0) {
		j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.fullConsideration','A4e value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(fullConsideration,'A4e value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	var fullConsiderationA5e = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleOnOtherAssets.fullConsideration')[0];
	if(dtaaSection.indexOf('A5e') != -1 && arr['A5e'] > 0 && fullConsiderationA5e.value == 0) {
		j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.saleOnOtherAssets.fullConsideration','A5e value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(fullConsiderationA5e,'A5e value should not be zero as there is an entry in DTAA table.',true);	
	}
	
	var totAmtStcgUnderDtaa = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54.totAmtStcgUnderDtaa')[0];
	if(dtaaSection.indexOf('A6') != -1 && arr['A6'] > 0 && totAmtStcgUnderDtaa.value == 0) {
		j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54.totAmtStcgUnderDtaa','A6 value should not be zero as there is an entry in DTAA table.');
		addErrorXHTML(totAmtStcgUnderDtaa,'A6 value should not be zero as there is an entry in DTAA table.',true);	
	}
}

//To validate CG item Wise values
function validateCGitemWise(){
	 
	var resStatus=document.getElementsByName('partAGEN1.filingStatus.residentialStatus')[0].value;
	if(resStatus == 'NRI'){
	  var arr = {'A1e':0,'A2e_111A':0,'A2e_115AD':0,'A3a':0,'A3b':0,'A4e':0,'A5e':0,'A6':0};
	  var A1eValue = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.capgainonAssets')[0].value;
	  var A3aValue = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTPaid')[0].value;
	  var A3bValue = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTNotPaid')[0].value;
	  var A4eValue = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.capgainonAssets')[0].value;
	  var A5eValue = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleOnOtherAssets.capgainonAssets')[0].value;
	  var A6Value = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54.totAmtStcgUnderDtaa')[0].value;
	  var table = document.getElementById('scheduleCGstcg2');
	  var rowCount = table.rows.length/10;
	  var A2e_111AValue = 0;
	  var A2e_115ADValue = 0;
	  for(var k=0; k<rowCount; k++) {
		  var section = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT['+ k +'].section')[0].value;
		  var amount = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT['+ k +'].capgainonAssets')[0].value;
		  if(section == '1A'){
			  A2e_111AValue =  parseInt(amount,10);
		  } 
		  if(section == '5AD1biip'){
			  A2e_115ADValue = parseInt(amount,10);
		}
	  } 
	  var tab = document.getElementById('scheduleStcgDtaa');
	  var rowCount = tab.rows.length -2;
	  for(var i=0; i<rowCount; i++) {
	    var itemIncluded = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.stcgUnderDtaa['+ i +'].itemIncluded')[0].value;
	    var amount = document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.stcgUnderDtaa['+ i +'].amount')[0].value;  
	   if(itemIncluded == 'A1e') {
	       arr['A1e'] = parseInt(arr['A1e'],10) +  parseInt(coalesce(amount),10);
	    } 
	    if(itemIncluded == 'A3a') {
		       arr['A3a'] = parseInt(arr['A3a'],10) +  parseInt(coalesce(amount),10);
		}
	    if(itemIncluded == 'A3b') {
		       arr['A3b'] = parseInt(arr['A3b'],10) +  parseInt(coalesce(amount),10);
		}
	    if(itemIncluded == 'A4e') {
		       arr['A4e'] = parseInt(arr['A4e'],10) +  parseInt(coalesce(amount),10);
		}
	    if(itemIncluded == 'A5e') {
		       arr['A5e'] = parseInt(arr['A5e'],10) +  parseInt(coalesce(amount),10);
		}if(itemIncluded == 'A6') {
		       arr['A6'] = parseInt(arr['A6'],10) +  parseInt(coalesce(amount),10);
		}if(itemIncluded == 'A2e_111A') {
			   arr['A2e_111A'] = parseInt(arr['A2e_111A'],10) +  parseInt(coalesce(amount),10);
		}if(itemIncluded == 'A2e_115AD') {
		       arr['A2e_115AD'] = parseInt(arr['A2e_115AD'],10) +  parseInt(coalesce(amount),10);
		}
		
		if(parseInt(A1eValue,10) != 0 &&  parseInt(arr['A1e'],10) <= 0) {
			  j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.capgainonAssets','Deduction under A1e must match with deduction in NRI table');
				addErrorXHTML('','Deduction under 54GB must match with deduction in table D',true);	
		  } if(parseInt(A3aValue,10) != 0 && parseInt(arr['A3a'],10) <=0 ) {
			  j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTPaid','Deduction under A3a must match with deduction in NRI table');
				addErrorXHTML('','Deduction under 54GB must match with deduction in table D',true);	
		  }
		 if(parseInt(A3bValue,10) != 0 && parseInt(arr['A3b'],10) <=0 ) {
			  j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTNotPaid','Deduction under A3b must match with deduction in NRI table');
				addErrorXHTML('','Deduction under 54GB must match with deduction in table D',true);	
		  }
		  if(parseInt(A4eValue,10) != 0 && parseInt(arr['A4e'],10) <= 0) {
			  j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.capgainonAssets','Deduction under A4e must match with deduction in NRI table');
				addErrorXHTML('','Deduction under 54GB must match with deduction in table D',true);	
		  }
		  if(parseInt(A5eValue,10) !=0 && parseInt(arr['A5e'],10) <=0 ) {
			  j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.saleOnOtherAssets.capgainonAssets','Deduction under A5e must match with deduction in NRI table');
				addErrorXHTML('','Deduction under 54GB must match with deduction in table D',true);	
		  }
		  if(parseInt(A6Value,10) !=0 && parseInt(arr['A6'],10) <=0) {
			  j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54.totAmtStcgUnderDtaa','Deduction under A6 must match with deduction in NRI table');
			  addErrorXHTML('','Deduction under 54GB must match with deduction in table D',true);	
		  }if(A2e_111AValue !=0 && parseInt(arr['A2e_111A'],10) <=0) {
			  j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT['+ i +'].section','Deduction under 111A must match with deduction in NRI table');
			  addErrorXHTML('','Deduction under 111A must match with deduction in table D',true);	
		  }if(A2e_115ADValue !=0 && parseInt(arr['A2e_115AD'],10) <=0) {
			  j.setFieldError('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT['+ i +'].section','Deduction under 115AD must match with deduction in NRI table');
			  addErrorXHTML('','Deduction under 115AD must match with deduction in table D',true);	
		  }
		
	  }  
	}

}

//To calculate Total Tax IT
function calculateTotalTaxIT(tableId){
	
	var tab1 = document.getElementById('scheduleIt');
    var noOfRows=tab1.rows.length;
	var sum = 0;
	var amt = 0;
		for ( var i = 0; i < (noOfRows-3); i++) {
			amt = document.getElementsByName('scheduleIT.taxPayment['+i+'].amt')[0].value;
			sum = eval(parseInt(sum,10) + parseInt(coalesce(amt),10));
		}
		
		document.getElementsByName('scheduleIT.taxPayment.totalTaxPayments')[0].value = parseInt(sum,10);
	
}

function mandateA6()
{
	
	var valueA13=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.fullConsideration50C')[0].value;
	var valueAb4=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.deductSec48.totalDedn')[0].value;
	var valueA1d=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleofLandBuild.exemptionOrDednUs54')[0].value;
	

	var valueA2ia=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT[0].fullConsideration')[0].value;
	var valueA2b4=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT[0].deductSec48.totalDedn')[0].value;
	var valueA2d=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.equityMFonSTT[0].lossSec94of7Or94of8')[0].value;
	

	var valueA3a=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTPaid')[0].value;
	var valueA3b=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRITransacSec48Dtl.nRItaxSTTNotPaid')[0].value;
	
	
	var valueA4a=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.fullConsideration')[0].value;
	var valueA44=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.deductSec48.totalDedn')[0].value;
	var valueA4d=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.nRISecur115AD.capgainonAssets')[0].value;
	
	
	var valueA5a=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleOnOtherAssets.fullConsideration')[0].value;
	var valueA54=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleOnOtherAssets.deductSec48.totalDedn')[0].value;
	var valueA5d=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.saleOnOtherAssets.capgainonAssets')[0].value;

	var valueA6=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unUtilizedCapGain54.totAmtStcgUnderDtaa')[0].value;
	
	var valueSTCG= valueA13+valueAb4+valueA1d+valueA2ia+valueA2b4+valueA2d+valueA3a+valueA3b+valueA4a+valueA44+valueA4d+valueA5a+valueA54+valueA5d+valueA6;
	
	

	var fieldSTCG=document.getElementsByName('scheduleCGPost45.shortTermCapGainPost45.unutilizedCapgainFlag')[0];
	var fieldLTCG=document.getElementsByName('scheduleCGPost45.LongTermCapGainPost45.unutilizedCapgainFlag')[0];

	if((valueSTCG!=null || valueSTCG!=undefined ) && valueSTCG >0 && fieldSTCG.value=="")
	{			
				addErrorXHTML(fieldSTCG,'Please select whether any amount of unutilized capital gain on asset transferred during the previous years in A6 of Schedule CG',true);
	}
	
}

function mandateB8()
{
	
	var valueBa3=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.fullConsideration50C')[0].value;
	var valueBb4=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.deductSec48.totalDedn')[0].value;
	var valueB1d=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofLandBuild.exemptionOrDednUs54')[0].value;
	
	var valueB2a=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofBondsDebntr.fullConsideration')[0].value;
	var valueBb4=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofBondsDebntr.deductSec48.totalDedn')[0].value;
	var valueB2d=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofBondsDebntr.exemptionOrDednUs54')[0].value;
	
	var valueB3a=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].fullConsideration')[0].value;
	var valueB34=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].deductSec48.totalDedn')[0].value;
	var valueB3d=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.proviso112Applicable[0].exemptionOrDednUs54S')[0].value;
	
	var valueB4a=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.ltcgWithoutBenefit')[0].value;
	var valueB4b=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIProvisoSec48.exemptionOrDednUs54')[0].value;
	
	var valueB5a=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115[0].fullConsideration')[0].value;
	var valueB54=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115[0].deductSec48.totalDedn')[0].value;
	var valueB5d=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRIOnSec112and115[0].exemptionOrDednUs54S')[0].value;
	
	var valueB6a=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.saleonSpecAsset')[0].value;
	var valueB6b=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.dednSpecAssetus115')[0].value;
	var valueB6d=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.saleOtherSpecAsset')[0].value;
	var valueB6e=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.nRISaleofForeignAsset.dednOtherSpecAssetus115')[0].value;
	
	var valueB7a=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofAssetNA.deductSec48.fullConsideration')[0].value;
	var valueB74=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofAssetNA.deductSec48.totalDedn')[0].value;
	var valueB7d=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.saleofAssetNA.exemptionOrDednUs54S')[0].value;
	
	
	var valueB9=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.ltcgUnderDtaa.totAmtLtcgUnderDtaa')[0].value;
	
	var valueB8=document.getElementsByName('scheduleCGPost45.longTermCapGainPost45.stcgUnderDtaa.totAmtStcgUnderDtaa')[0].value;
	
	var fieldLTCG=document.getElementsByName('scheduleCGPost45.LongTermCapGainPost45.unutilizedCapgainFlag')[0];
	
	var valueLTCG=valueBa3+valueBb4+valueB1d+valueB2a+valueBb4+valueB2d+valueB3a+valueB34+valueB3d+valueB4a+valueB4b+valueB5a+valueB54+valueB5d+valueB6a+valueB6b+valueB6d+valueB6e+valueB7a+valueB74+valueB7d+valueB9+valueB8;
	
	if((valueLTCG!=null || valueLTCG!=undefined ) && valueLTCG >0 && fieldLTCG.value=="")
	{			
			addErrorXHTML(fieldLTCG,'Please select whether any amount of unutilized capital gain on asset transferred during the previous years in B8 of Schedule CG',true);
	}
}

//To get Ifsc Bank Details
function getIfscBankDetails(elem){
	
	var position = parseInt(elem.name.substring(elem.name.indexOf("[") + 1, elem.name.indexOf("]")));
			
	var  ifscCode = document.getElementsByName('partBTTI.bankAccountDtls.otherBankDetails['+position+'].ifscCode')[0].value;
	
	document.getElementsByName('partBTTI.bankAccountDtls.otherBankDetails['+position+'].bankName')[0].value = main.getBankName(ifscCode);
		
	
}

//To get Ifsc Bank Name
function getIfscBankName(field){
	
	document.getElementsByName('partBTTI.bankAccountDtls.priBankDetails.bankName')[0].value = main.getBankName(field.value);
		
	
}

//To enable Passport
function enablePassport()
{
	var status = document.getElementsByName('partAGEN1.personalInfo.status')[0].value;
	 if(status=='I')
	  {
	    document.getElementsByName('partAGEN1.personalInfo.passportNumber')[0].disabled=false;
	    document.getElementsByName('partAGEN1.personalInfo.passportNumber')[0].readOnly=false;
	    
	  }	  
	  if(status=='H')
	  {	    
	    document.getElementsByName('partAGEN1.personalInfo.passportNumber')[0].disabled=true;
	    document.getElementsByName('partAGEN1.personalInfo.passportNumber')[0].readOnly=true;
	    document.getElementsByName('partAGEN1.personalInfo.passportNumber')[0].value='';
	  }
}

//To validate Passport
function validatePassport()
{
	
		var value = document.getElementsByName('partAGEN1.personalInfo.passportNumber')[0].value;
		
		if(value =='00000000000000')
			{	
				addErrorXHTML(document.getElementsByName('partAGEN1.personalInfo.passportNumber')[0],'Passport number should be alpha-numeric',true);
				j.setFieldError('partAGEN1.personalInfo.passportNumber','Passport number should be alpha-numeric');				
			}
}

//To validate Passport for Spaces
function validatePassportforSpaces() {
	var value = document.getElementsByName('partAGEN1.personalInfo.passportNumber')[0].value;
    if (value.trim() == "") {
       
    	addErrorXHTML(document.getElementsByName('partAGEN1.personalInfo.passportNumber')[0],'Passport number should be alpha-numeric',true);
		j.setFieldError('partAGEN1.personalInfo.passportNumber','Passport number should be alpha-numeric');	
    }
    
}

//To open Save file dialog
function popupWithOk()
{
	  j.popup();
}