AGE_1=0
AGE_2=0
AFR=1
Lead=false;
Annuity=0
ProNo=0

function parseQuerystring( parameterName )
{
   var lletter, fletter;
   var querystring, parameterValue, rSpace;
   
   querystring = document.location.search;
   parameterValue = "";
   // remove "?"
   if ( querystring.length > 1 ) 
   {
        querystring = querystring.substr(1);
        
        fletter = querystring.indexOf(parameterName);
        if(fletter != -1)
        {
             // move past parameterName and =
             fletter += parameterName.length + 1;
             lletter = querystring.indexOf('&', fletter);
             if(lletter == -1)
             {
                  lletter = querystring.length;
             }
             parameterValue = querystring.substring(fletter,lletter);
             rSpace = new RegExp(" ","g");
             parameterValue = parameterValue.replace(rSpace, "+");
        }
   }
   return parameterValue;
}

function START(){
	document.PS.url.options[0].selected=true
	ProNo=parseInt(document.cres.Pro.value)
	AFR1=parseInt(document.cres.AFR.value)+1
	//document.cres.uID.value=="") Reset()
   if(ProNo == 2 || ProNo == 5 || ProNo == 10 || ProNo == 12) {
	 iLives = 2;
   }else {
     iLives = 1;
   }
	if(document.cres.Amount.value!="") checkDollar(document.cres.Amount)
	
	if (ProNo >= 9 && ProNo <= 12) {
	  checkPD(document.cres.PayoutDate, true);
	  if(document.cres.Age1.value != null && document.cres.Age1.value != "" && (iLives == 1 || (iLives == 2 && document.cres.Age2.value != ""))) {

  		if(document.cres.Age1.value != "")
		  checkInput(document.cres.BOD1)
		if(iLives == 2 && document.cres.Age2.value != "")
		  checkInput(document.cres.BOD2)
		  
	    getACGA(document.cres.ACGA, ProNo);
	  } else {
	    if(document.cres.ACGA)
		  document.cres.ACGA.value = ""; 
	  }
	}
	
}

function ReCall(){
	document.cres.reset()
	if(document.cres.Amount.value!="") checkDollar(document.cres.Amount)
	if(document.cres.Term.value!="" && Lead==false) checkInput(document.cres.Term)

}
function change(form, selectStr) {
   if (form.url.selectedIndex >1){
     document.cres.action = form.url.value ; //"Calc2.jsp&" + selectStr;
	 document.cres.submit();
   }
   
   
   //window.location.href = form.url.options[form.url.selectedIndex].value;
}

function Reset(){
	document.cres.GiftDate.value=getToday()
	document.cres.AFR.options[0].selected=true
	document.cres.Donor.value=""
	if(ProNo==1 || ProNo==2 || ProNo==4 || ProNo==5 || ProNo==9 || ProNo==10){
		document.cres.Name1.value=""
		document.cres.BOD1.value=""
		document.cres.Age1.value=""
	}
	if(ProNo==2 || ProNo==5 || ProNo==10){
		document.cres.Name2.value=""
		document.cres.BOD2.value=""
		document.cres.Age2.value=""
	}
	if(ProNo==3 || ProNo==6 || ProNo==7 || ProNo==8){
		document.cres.Term.value=""
		document.cres.Benef.value=""
	}
	if(ProNo==9 || ProNo==10 || ProNo==11 || ProNo==12){
		document.cres.fBasis.value=""
		document.cres.PayoutDate.value=getToday()
		document.cres.ACGA.value=""
	}
	if (ProNo!=9 && ProNo!=10 && ProNo!=11 && ProNo!=12) {
	  document.cres.Payout.value=""	
	}
	document.cres.Amount.value=""
	document.cres.Frequency[1].checked=true
	document.cres.GiftDate.focus()
}

function RunHelp(I, WebID){
	popup("CalcHelp.jsp?T="+I + "&WebID=" + WebID,505,400);
}
function popup(url,w,h) {
     winame = "GiftLaw";
        
     winparams = 'toolbar=0,location=0,directories=0,status=0,menubar=0,resizable=0,scrollbars=0,width=' + w + ',height=' + h;
     winame = open(url,winame,winparams);
}
function checkAll(Obj){

	GO=true
	for(i=0;i<Obj.length;i++){
		if(Obj.elements[i].value=="" && Obj.elements[i]!=document.cres.BOD1 && Obj.elements[i]!=document.cres.uID){
			alert("Please enter a value")
			Obj.elements[i].focus()
			GO=false
			break
		}
	}
	if(document.cres.Term.value!="" && Lead==false) {
		if(!checkRange(document.cres.Term,1,20)) GO=false
	}
 	if (GO) {
	  if (ProNo >= 9 && ProNo <= 12)
	    checkPD(document.cres.PayoutDate);
	}

  if(GO){
	  temp=document.cres.Amount.value
		while(temp.indexOf(",")!=-1) temp=temp.replace(",","")
		document.cres.Amount.value=temp
		if (ProNo == 9 || ProNo == 10 || ProNo == 11 || ProNo == 12) {
		  temp=document.cres.fBasis.value
		  while(temp.indexOf(",")!=-1) temp=temp.replace(",","")
		  document.cres.fBasis.value=temp
		}
		document.cres.Rate.value=document.cres.AFR.options[document.cres.AFR.selectedIndex].text
		Obj.submit()
	}
	
}	
function checkGD(Obj){

	EM = new Array ("","January","February","March","April","May","June","July","August","September","October","November","December")
	m = new Array(5)	
	y = new Array(5)
	PASS=false
	GD = new Date(document.cres.GiftDate.value)

	if(GD > new Date("6/30/1999")) {
  	  TD = new Date()
	  M1 = GD.getMonth()+1
	  m[1] = TD.getMonth()+1
	  Y1 = GD.getFullYear()
	  y[1] = TD.getFullYear()
	  for(i=1;i<=2;i++){
		if(m[i]-1>=1){
			y[i+1]=y[i]
			m[i+1]=m[i]-1
		} else {
			y[i+1]=y[1]-1
			m[i+1]=12
		}
	  }

	  for(i=1;i<=3;i++){
		if(Y1==y[i] && M1==m[i]){
			PASS=false
			AFR=i
			document.cres.AFR.options[i-1].selected=true
			document.cres.AFR1.value=i-1
			document.cres.AFR2.value=i-1
		}
	  }
      	  if(!PASS){
		//document.location.href="glcalcb.jsp?P=" + ProNo + "&WebID=" + parseQuerystring("WebID") + "&GiftDate=" + document.cres.GiftDate.value 
	        document.cres.action = "glcalcb.jsp?P=" + ProNo + "&WebID=" + parseQuerystring("WebID");
		document.cres.submit();
	  } else {
		changeAFR()		
	  }
        }else {
          Obj.value="";
	  Obj.focus();
          alert("Gift Date must be after July 1, 1999");
        }
}

function isDeferred(paydate, giftdate) { 
  //checks if paydate is deffered 1 year after giftdate
/*
  if(timeDifference(paydate, giftdate) < 365) {
    return false; 
  }else {
    return true; 
  }
*/
//leapyear
  if(giftdate.getDate() == 29 && giftdate.getMonth() == 1) {
    if(timeDifference(paydate, giftdate) < 366) {
      return false;
    } else {
      return true;
    }
  } else {
    if(paydate.getYear() <= giftdate.getYear()) {
      return false;
    } 

    if(paydate.getYear() == giftdate.getYear()+1) {
      if(paydate.getMonth() < giftdate.getMonth()) {
        return false;
      } else if(paydate.getMonth() == giftdate.getMonth()) {
        if(paydate.getDate() < giftdate.getDate()) {
          return false;
        }
      }
    }
    return true; 
  }
}

function checkPD(Obj, bStart){
  PASS=false
  PD = new Date(document.cres.PayoutDate.value)
  GD = new Date(document.cres.GiftDate.value)
  TD = GD;
  var tempInt;
  	
  //if (PD.getMonth() >= GD.getMonth()	&& PD.getDay() >= GD.getDay() && PD.getYear() >= GD.getYear() )
  if (PD >= GD) {
    if(ProNo == 11 || ProNo == 12) {
      //check if payment is deferred one year
      if(isDeferred(PD,GD)) {
        PASS = true;
      }
    } else {
  	if (document.cres.Frequency[0].checked) {
  		TD.setMonth(GD.getMonth()+1);
  		if (PD <= TD)
  	  	  PASS=true;
  	}
  	else if (document.cres.Frequency[1].checked) {
  	  TD.setMonth(GD.getMonth()+3)  
  		if (PD <= TD)
  		  PASS=true
  	}
  	else if (document.cres.Frequency[2].checked) {
  		TD.setMonth(GD.getMonth()+6)
  		if (PD <= TD)
  			PASS=true
  	}
  	else {
  		TD.setFullYear(GD.getFullYear()+1)
  		if (PD <= TD)
  			PASS=true
  	}
    }
  }
   	
  if(!PASS){
    if(ProNo == 11 || ProNo == 12) {
	  TD.setTime(GD.getTime() + (367*24*60*60*1000));
	  document.cres.PayoutDate.value = parseInt(TD.getMonth()+1)+"/"+parseInt(TD.getDate())+"/"+parseInt(TD.getFullYear());
	  if (!bStart){
	    alert("First Payment Must Be Deferred at Least a Year From the Gift Date.  Please enter a new first payment date.");
	    document.cres.PayoutDate.focus()
	  }
	}else {
	  Obj.value=parseInt(TD.getMonth()+1)+"/"+parseInt(TD.getDate())+"/"+parseInt(TD.getFullYear())
	  if (!bStart) {
		alert("Payout Date must be after Gift Date but within one payment period. (one month, three months, six months, twelve months). Please enter a new Payout Date")
		Obj.focus()
          }
	}
  }else {
    if (!bStart && document.cres.ACGA.value == "") 
	  getACGA(document.cres.ACGA, ProNo);
  }
	
}


function getToday(){
	TD = new Date()
	TODAY = (parseInt(TD.getMonth())+1) + "/" + parseInt(TD.getDate()) + "/" + parseInt(TD.getFullYear())
	return TODAY
}		
		

function checkDate(Obj) {
	 temp = new Date(Obj.value)
         tempY = parseInt(temp.getFullYear())
	 temp = temp.getMonth()+1+"/"+temp.getDate()+"/"+temp.getFullYear()
         if (temp == "NaN/NaN/NaN" || tempY<1900 || tempY>2100) {
      		alert("Please enter a valid date.")
		if(Obj==document.cres.GiftDate){
			Obj.value=getToday()
		} else {
			Obj.value=""
		}
		Obj.focus()
		return false
         } else {
      	        Obj.value=temp
		return true
         }
}
function checkLeapYear(Y){
	if(Y%4==0 && Y%100!=0) { 
		return 1
	}else {
		if(Y%400==0) { 
			return 1
		} else {
			return 0
		}
	}
}
function countDate(M1,D1,Y1,M2,D2,Y2){
	LifeD=0
     	MD = new Array (0,31,28,31,30,31,30,31,31,30,31,30,31)
	if(Y1!=Y2){
	     	LifeD=LifeD+MD[M1]-D1+1
     		for(i=M1+1;i<=12;i++){
     			LifeD=LifeD+MD[i]
	     	}
     		if(M1<=2) LifeD=LifeD+checkLeapYear(Y1)
      
	     	for(i=Y1+1;i<Y2;i++){
     			if(checkLeapYear(i)) {
     				LifeD=LifeD+366
	     		}else {
     				LifeD=LifeD+365
     			}
	     	}
     		for(i=1;i<M2;i++){
     			LifeD=LifeD+MD[i]
	     	}
     		LifeD=LifeD+D2-1
	     	if(M2>=2) LifeD=LifeD+checkLeapYear(Y2)
	}else {
		if(M1==M2){
			LifeD=D2-D1
		}else {
			LifeD=LifeD+MD[M1]-D1+1
			for(i=M1+1;i<M2;i++){
				LifeD=LifeD+MD[i]
			}
			LifeD=LifeD+D2-1
			if(M1<=2 && M2>2) LifeD=LifeD+checkLeapYear(Y1)
		}
	}
	return LifeD
}

function checkDate2(Obj,Obj2){
         LifeD=0
	 gd = new Date(document.cres.GiftDate.value)	
	 temp = new Date(Obj.value)
	 tempY=temp.getFullYear()
         temp2 = temp.getMonth()+1+"/"+temp.getDate()+"/"+tempY
         if (temp2 == "NaN/NaN/NaN" || tempY<1890 || tempY>2100) {
	      	Obj.value=""
		Obj2.value=""
		return false
         } else {
		Y1=parseInt(gd.getFullYear())
		Y2=parseInt(temp.getFullYear())
		M1=parseInt(gd.getMonth())+1
		M2=parseInt(temp.getMonth())+1
		D1=parseInt(gd.getDate())
		D2=parseInt(temp.getDate())
		if(Y1>=Y2){
			LifeD=countDate(M2,D2,Y2,M1,D1,Y1)
			Obj2.value=Math.round(LifeD/365.25)
			if(parseInt(Obj2.value)>109){
				 alert("Please enter a age less than or equal to 109")
				 Obj.value=""
				 Obj2.value=""
				 Obj.focus()
				 return false
			}
			if(Obj==document.cres.BOD1) {
				AGE_1=Obj2.value
			} else {
				AGE_2=Obj2.value
			}
		} else {
			Obj.value=""
			Obj2.value=""
		}
         }
	 Obj.value=temp2
	 return true 	
}

function checkDate3(Obj,Obj2){
	age=parseInt(Obj.value)
	if(Obj==document.cres.Age1) {
		age2=AGE_1
	} else {
		age2=AGE_2
	}
	temp = new Date(Obj2.value)
	gd = new Date(document.cres.GiftDate.value)
	Y1=parseInt(gd.getFullYear())
	M1=parseInt(gd.getMonth())
	D1=parseInt(gd.getDate())

	temp2 = temp.getMonth()+1+"/"+temp.getDate()+"/"+temp.getFullYear()
	if (temp2 != "NaN/NaN/NaN") {
		Y2=parseInt(temp.getFullYear())
		M2=parseInt(temp.getMonth())
		D2=parseInt(temp.getDate())
		temp2 = temp.getMonth()+1+"/"+temp.getDate()+"/"+(Y2+(age2-age))
	} else {
		temp2 = (M1+1)+"/"+(D1)+"/"+(Y1-age)
	}


	if(Obj==document.cres.Age1) {
		AGE_1=Obj.value
	} else {
		AGE_2=Obj.value
	}
	Obj2.value=temp2

}


function checkRange(Obj,S,L){
   
	temp = parseFloat(Obj.value)
        temp2 = ""+temp
        if(temp<S || temp>L || temp2 == "NaN"){
      	alert("Please enter a value greater than or equal to "+S+" and less than or equal to "+L)
      	Obj.value=""
      	Obj.focus()
		return false
         } else {
      	Obj.value=temp
		return true
         }
	   
}
function checkBlank(Obj){
	   temp = Obj.value
         if(temp == ""){
      	alert("Please enter a value")
		Obj.value=""
		Obj.focus()
		return false
         } else {
      	Obj.value=temp
		return true
         }
}
function checkChar(Obj,Dtype){
  	var checkOK = ""
	switch(Dtype){
		case 1:
			checkOK = "0123456789."
			break
		case 2:
			checkOK = "0123456789.,$"
			break
		case 3:
			checkOK = "0123456789/"
			break
		case 4:
			checkOK = "0123456789"
	}
       
       var checkStr = Obj.value
       var allValid = true
       var decPoints = 0
       var allNum = ""
       for (i = 0;  i < checkStr.length;  i++)
       {
         ch = checkStr.charAt(i)
         for (j = 0;  j < checkOK.length;  j++)
           if (ch == checkOK.charAt(j))
             break
         if (j == checkOK.length)
         {
           allValid = false
           break;
         }
         if (ch == ".")
         {
           allNum += "."
           decPoints++
         }
         else if (ch != ",")
           allNum += ch
       }
       if (!allValid)
       {
         alert("Please enter a valid characters")
         if(Obj==document.cres.GiftDate) {
		Obj.value=getToday()
	 } else {
		Obj.value=""
	 }
         Obj.focus()
         return false
       } else {
         return true	
       }
}

function checkDollar(Obj){
	   temp = new String(Obj.value)
         temp = temp.substring(temp.indexOf("$")+1,temp.length)
	   while(temp.indexOf(",")!=-1) temp = temp.replace(",","")
	   temp = parseFloat(temp)
	   
         temp = Math.floor(100*temp)/100
         temp = String(temp)
         if (temp.indexOf(".") == -1) {
         	temp = temp + ".00"
         }
         if (temp.indexOf(".") == temp.length -2) {
         	temp = temp + "0"
         }
         if (temp == "0.00") {
         	temp = ""
         }
	   if (temp!="" && temp.length>6){
		j=temp.length-3
		j=j-3
		temp2=""
		while(j>0){
			temp2=","+temp.substr(j,3)+temp2	
			j=j-3
		}
		j=j+3
		temp2=temp.substring(0,j)+temp2+temp.substr(temp.length-3,3)
	   } else {
	   	temp2=temp
	   }
	   
         Obj.value = temp2
	   return true
}

function checkInput(Obj){
	P=false
  if(Obj==document.cres.GiftDate){
		if(checkChar(Obj,3)) {
			if(checkDate(Obj)) checkGD(Obj);
		}
  } 
  if(Obj==document.cres.PayoutDate){
    if(checkChar(Obj,3)) {
      if(checkDate(Obj)) checkPD(Obj, false);
    }
  } 
  
  if(Obj==document.cres.Donor){
		checkBlank(Obj)
  } 

  if(Obj==document.cres.Name1){
		checkBlank(Obj)
  } 

  if(Obj==document.cres.Benef){
		checkBlank(Obj)
  }

  if(Obj==document.cres.BOD1){
		if(checkChar(Obj,3)) checkDate2(Obj,document.cres.Age1)
  } 

  if(Obj==document.cres.Age1){
		if(checkChar(Obj,4)) {
			P=checkRange(Obj,20,109)
			if(P) checkDate3(Obj,document.cres.BOD1)
		} 
  } 

  if(Obj==document.cres.BOD2){
		if(checkChar(Obj,3)) checkDate2(Obj,document.cres.Age2)
  } 

  if(Obj==document.cres.Age2){
		if(checkChar(Obj,4)) {
			P=checkRange(Obj,20,109)
			if(P) checkDate3(Obj,document.cres.BOD2)
		}
  } 

  if(Obj==document.cres.Term){
		if(checkChar(Obj,1)){
			if(Lead){
				checkRange(Obj,1,35)
			} else {
				checkRange(Obj,1,20)
			}
		}
  } 

  if(Obj==document.cres.Amount){
		P=checkChar(Obj,2)
		if(P) checkDollar(Obj)
  } 

  if(Obj==document.cres.fBasis){
		P=checkChar(Obj,2)
		if(P) checkDollar(Obj)
  } 

  if(Obj==document.cres.Payout){
		if(checkChar(Obj,1)) {
			if(ProNo!=7 && ProNo!=8) checkRange(document.cres.Payout,5,50)
			if(ProNo==4) checkPB(1)
			if(ProNo==5) checkPB(2)
		}
  } 

  if(Obj==document.cres.Frequency[0] || Obj==document.cres.Frequency[1] || Obj==document.cres.Frequency[2] || Obj==document.cres.Frequency[3]){
		//alert("Please enter a number less than or equal to "+Ann)
			if(ProNo==4) checkPB(1)
			if(ProNo==5) checkPB(2)
			if(ProNo==9 || ProNo==10 || ProNo==11 || ProNo==12)
		     	  checkPD(document.cres.PayoutDate, false)
  } 

  if(Obj == document.cres.ACGA) {
	  P=checkChar(Obj,1);
  }

}

function checkAge(Obj){
	if(Obj==document.cres.Age1 && document.cres.Age1.value!="") AGE_1=parseInt(document.cres.Age1.value)
	if(Obj==document.cres.Age2 && document.cres.Age2.value!="") AGE_2=parseInt(document.cres.Age2.value)
}

function checkInput2(Obj){
	if(Obj.value=="") Obj.focus()
}

function changeAFR(){
	if(document.cres.GiftDate.value==""){
		document.cres.GiftDate.focus()
	} else {
		document.cres.Rate.value=document.cres.AFR.options[document.cres.AFR.selectedIndex].text
		if(document.cres.AFR.selectedIndex<document.cres.AFR2.value){
				document.cres.AFR1.value=document.cres.AFR2.value
				document.cres.AFR.options[document.cres.AFR2.value].selected=true
		} else {
				document.cres.AFR1.value=document.cres.AFR.selectedIndex
		}

		
	}
}
function checkPB(Life){
	Ann=parseFloat(document.cres.Payout.value)/100.0
	
	if(checkProbability(Life,Ann)>4.95){
		Ann=Ann-0.01
		while(checkProbability(Life,Ann)>4.95 && Ann>0){
			Ann=Ann-0.01
		}
		if(Ann<0) Ann=0;
		Ann=Ann+0.001
		while(checkProbability(Life,Ann)<4.95 && Ann>0){
			Ann=Ann+0.001
		}
		Ann=Ann-0.0001
		while(checkProbability(Life,Ann)>4.95 && Ann>0){
			Ann=Ann-0.0001
		}
		Ann=Ann-0.0005
		Ann=RoundDouble(Ann*100,2)
		if(Ann>=5.0) {
			alert("Maximum Payout Rate For 5% Probability Test Under Revenue Ruling 77-454.  Please Note!  This maximum rate is correct only if all the entry data is correct.  If any entry data is not correct, this number may be too high and the IRS might contest the tax deduction.  While the method in the Crescendo 5% probability test has been developed in consultation with the Actuarial Office of the IRS, the professional advisor of the donor must be notified that the maximum payout rate is being used. Please enter a number less than or equal to "+Ann);
			document.cres.Payout.value=Ann
			document.cres.Payout.focus()
	 	}else if (Ann!="" && Ann>0.0) {
		  alert("Maximum Payout Rate For 5% Probability Test Under Revenue Ruling 77-454 is less than minimum required 5% payout.  Trust not permitted with this duration.");
			document.cres.Payout.value=""
			document.cres.Payout.focus()	  
		}
		return false

	}
	return true
}

function checkProbability(Life,Ann){
MT=new Array (100000.0, 99064.0 ,98992.0, 98944.0, 98907.0, 98877.0, 8850.0, 98826.0, 98803.0, 98783.0, 98766.0, 98750.0, 98734.0, 98713.0, 98681.0, 98635.0, 98573.0, 98497.0, 98409.0, 98314.0, 98215.0, 98113.0, 98006.0, 97896.0, 97784.0, 97671.0, 97556.0, 97441.0, 97322.0, 97199.0, 97070.0, 96934.0, 96791.0, 96642.0, 96485.0, 96322.0, 96150.0, 95969.0, 95780.0, 95581.0, 95373.0, 95156.0, 94928.0, 94687.0, 94431.0, 94154.0, 93855.0, 93528.0, 93173.0, 92787.0, 92370.0, 91918.0, 91424.0, 90885.0, 90297.0, 89658.0, 88965.0, 88214.0, 87397.0, 86506.0, 85537.0, 84490.0, 83368.0, 82169.0, 80887.0, 79519.0, 78066.0, 76531.0, 74907.0, 73186.0, 71357.0, 69411.0, 67344.0, 65154.0, 62852.0, 60449.0, 57955.0, 55373.0, 52704.0, 49943.0, 47084.0, 44129.0, 41091.0, 37994.0, 34876.0, 31770.0, 28687.0, 25638.0, 22658.0, 19783.0, 17046.0, 14466.0, 12066.0, 9884.0, 7951.0, 6282.0, 4868.0, 3694.0, 2745.0, 1999.0, 1424.0, 991.0, 672.0, 443.0, 284.0, 175.0, 105.0, 60.0, 33.0, 17.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);

Term=0.0
temp= new Array(5)
for(i=0;i<5;i++) temp[i] = new Array(120)
A_F_R=parseFloat(document.cres.AFR.options[document.cres.AFR.selectedIndex].value)/100.0

if(document.cres.Frequency[0].checked) Term=12.0
if(document.cres.Frequency[1].checked) Term=4.0
if(document.cres.Frequency[2].checked) Term=2.0
if(document.cres.Frequency[3].checked) Term=1.0

sTemp=document.cres.Amount.value
Amount=parseFloat(sTemp.replace(",",""))
Age1=parseInt(document.cres.Age1.value)
Age2=0
if (Life==2) Age2=parseInt(document.cres.Age2.value)

var EofP=0.0;
var TEMP;
var YtoE=0;
var Age1_1=0;
var Age2_1=0;
var P1=0.0;
var P2=0.0;
var Prob=0.0;
		
EofP=A_F_R/(Term*(Math.pow(1.0+A_F_R,1.0/Term)-1.0));
temp[2][0]=Amount;
temp[0][1]=temp[2][0]*A_F_R;
temp[1][1]=Ann*EofP*Amount;
TEMP=temp[2][0]+temp[0][1]-temp[1][1];
    	
if(TEMP>0){
	temp[2][1]=TEMP;
} else {
      temp[2][1]=0;
}
for(i=2;i<108;i++){
   temp[0][i]=temp[2][i-1]*A_F_R;
   if(temp[2][i-1]==0) {
       temp[1][i]=0.0;
   } else {
       temp[1][i]=temp[1][i-1];
   }
   TEMP=temp[2][i-1]+temp[0][i]-temp[1][i];
   if(TEMP>0){
       temp[2][i]=TEMP;
   } else {
       temp[2][i]=0;
       YtoE=i;
       break;
   }
}
Age1_1=Age1+YtoE;
if(Age1_1>110) Age1_1=110;
P1=MT[Age1_1]/MT[Age1];
if(Life==2){
    Age2_1=Age2+YtoE;
    if(Age2_1>110) Age2_1=110;
    P2=MT[Age2_1]/MT[Age2];
}
if(Life==2){
    Prob=1.0-((1.0-P1)*(1.0-P2));
} else {
    Prob=P1;
}
        
	Prob=RoundDouble(Prob,4)*100-0.05
	return Prob        
}
function RoundDouble(D, I){
			D=D*(Math.pow(10,I));
			D=Math.round(D);
			D=D/(Math.pow(10,I));
			return(D);					
}



function CheckLife(iLives, iProgram, sAction){

  if (iLives == 1){
    if (document.cres.rTrustType[1].checked){
	   document.cres.action = sAction + "&P=" + (iProgram + 1);
	   document.cres.submit();
    }
  }
  else {
    if (document.cres.rTrustType[0].checked){
      document.cres.action = sAction + "&P=" + (iProgram - 1);
      document.cres.submit();
    }
  }
  
}

function getACGA(Obj, P){  

  if ( ((parseInt(document.cres.ilvs.value) == 1 && document.cres.Age1.value != "") || (parseInt(document.cres.ilvs.value) == 2 && document.cres.Age2.value != "")) && (ProNo >= 9 && ProNo <= 12)) {
    var PayD = new Date(document.cres.PayoutDate.value);
    var GiftD = new Date(document.cres.GiftDate.value);
    var StartD = new Date();
    var JulyD = new Date("07/01/2001");
    var yearDiffPeriod = 1;
    var oldDiffTable = new Array(   "1.000",   "1.058",   "1.118",   "1.183",   "1.251",
                                  "1.323",   "1.399",   "1.479",   "1.564",   "1.654",
			          "1.749",   "1.850",   "1.956",   "2.068",   "2.187",
				  "2.313",   "2.446",   "2.587",   "2.736",   "2.893",
				  "3.059",   "3.235",   "3.421",   "3.618",   "3.826",
				  "4.046",   "4.278",   "4.524",   "4.785",   "5.060",
				  "5.351",   "5.658",   "5.984",   "6.328",   "6.692",
				  "7.076",   "7.483",   "7.914",   "8.369",   "8.850",
				  "9.359",   "9.897",  "10.466",  "11.068",  "11.704",
				 "12.377",  "13.089",  "13.841",  "14.637",  "15.479",
			         "16.369",  "17.310",  "18.305",  "19.358",  "20.471",
			         "21.648",  "22.893",  "24.209",  "25.601",  "27.073",
			         "28.630",  "30.276",  "32.017",  "33.858",  "35.805",
				 "37.864",  "40.041",  "42.343",  "44.778",  "47.353",
			         "50.076",  "52.955",  "56.000",  "59.220",  "62.625",
			         "66.226",  "70.034",  "74.061",  "78.319",  "82.823",
			         "87.585",  "92.621",  "97.947", "103.579", "109.535",
				"115.833", "122.493", "129.537", "136.985", "144.862",
			        "153.191", "162.000", "171.315", "181.165", "191.582",
				"202.598", "214.248", "226.567", "239.595", "253.371",
				"267.940")
 
    //the number of days between giftdate and the paydate
    dayDiffGDPD = Math.round(timeDifference(PayD,GiftD));
    //calculate differal period
    if(document.cres.Frequency[3].checked) {
      yearDiffPeriod = (dayDiffGDPD/365.25) - 1; 
    }else if(document.cres.Frequency[2].checked) {
      yearDiffPeriod = (dayDiffGDPD/365.25) - 0.5; 
    }else if(document.cres.Frequency[1].checked) {
      yearDiffPeriod = (dayDiffGDPD/365.25) - 0.25; 
    }else if(document.cres.Frequency[0].checked) {
      yearDiffPeriod = (dayDiffGDPD/365.25) - (1/12); 
    } // end if frequency

    //calculate StartDate from differal period
    StartD.setTime(GiftD.getTime() + (yearDiffPeriod*365.25*1000*60*60*24));
    document.cres.StartDate.value = (StartD.getMonth()+1) + "/" + StartD.getDate() + "/" + StartD.getFullYear();

    if(P == 9||P == 11) { 
      if(P == 11) {
        birthDay1 = new Date(document.cres.BOD1.value); 
        //calculate the Payment Age for first person
        document.cres.PaymentAge1.value = Math.floor(timeDifference(PayD,birthDay1));
        //find lowage from start date
        lowAge = Math.round(timeDifference(StartD,birthDay1)/365.25)    
        document.cres.AnnStartAge1.value = lowAge;

        if(lowAge < 20) {
          lowAge = 20;
        }
        if(lowAge > 109) {
          lowAge = 109;
        }
      }else {
        lowAge = document.cres.Age1.value;
        if(lowAge < 20) {
          lowAge = 20;
        }
        if(lowAge > 109) {
          lowAge = 109;
        }
      } // end if P==11
      rateACGA = acga1[lowAge];   

    }else if (P == 10 || P == 12){
      var lowAge = 0;
      var highAge = 0;
      if(document.cres.Age2.value != "")
        highAge = parseInt(document.cres.Age2.value);
      lowAge = parseInt(document.cres.Age1.value);
      if(highAge < 20) {
        highAge = 20; 
      }else if(highAge > 109) {
        highAge = 109;
	  } 
      if(lowAge < 20) {
        lowAge = 20; 
	  }else if(lowAge > 109) {
        lowAge = 109;
	  }
      if(lowAge > highAge) {
        var tempAge = lowAge;
        lowAge = highAge;
        highAge = tempAge;
      }
      if(P==12) {
        //find lowage, highage from StartDate
        birthDay1 = new Date(document.cres.BOD1.value)

        document.cres.PaymentAge1.value = Math.floor(timeDifference(PayD,birthDay1)/365.25);
        if(document.cres.BOD2.value != "")
          birthDay2 = new Date(document.cres.BOD2.value)
        else
          birthDay2 = new Date("07/01/2001")
        //calculate the Payment Age for first person
        document.cres.PaymentAge2.value = Math.floor(timeDifference(PayD,birthDay2)/365.25);
        var firstAge = Math.round(timeDifference(StartD,birthDay1)/365.25);
        document.cres.AnnStartAge1.value = firstAge;
        var secondAge = Math.round(timeDifference(StartD,birthDay2)/365.25);
        document.cres.AnnStartAge2.value = secondAge;
        if(firstAge < secondAge) {
          lowAge = firstAge;
	      highAge = secondAge;
        }else {
          lowAge = (secondAge);
	      highAge = (firstAge);
        }
        if(lowAge < 20) {
          lowAge = 20;
        }
        if(lowAge > 109) {
          lowAge = 109
        }
        if(highAge < 20) {
          highAge = 20;
        }
        if(highAge > 109) {
          highAge = 109;
        }
      } // end if P==12
      highAge -= 20;
      lowAge -= 20;
      rateACGA = acga2[lowAge][highAge];
    } // end if P==9 or P==11

    if(P == 11 || P == 12) {
      //first figure out what formula to use
      if(GiftD < JulyD) {

        //look up the differal factor in the table  
        diffFactor = oldDiffTable[Math.floor(yearDiffPeriod)] 
      }else {

        //get diff Factor Table
        var diffFactor2001 = new Array("1.0575","1.0550","1.0525","1.0500");
        var diffFactor2003 = new Array("1.0525","1.0500");
        var diffFactor2003_2 = new Array("1.0500");
        var diffFactor2006 = new Array("1.0525");
        var diffFactor2008 = new Array("1.0475");
        var diffFactor2009 = new Array("1.0425");
        var diffFactor2010 = new Array("1.045");
        var diffFactor2011 = new Array("1.04");		
        var January2003 = new Date("01/01/2003");
        var July2003 = new Date("07/01/2003");
        var July2006 = new Date("07/01/2006");
        var July2008 = new Date("07/01/2008");
        var Feb2009 = new Date("02/01/2009");
        var July2010 = new Date("07/01/2010");
        var July2011 = new Date("07/01/2011");

        if(GiftD < January2003) {

          if((yearDiffPeriod) < 20) {
            diffFactor = Math.pow(diffFactor2001[0],(yearDiffPeriod));
          }else {
            diffFactor = Math.pow(diffFactor2001[0],20);
          }

          if((yearDiffPeriod) > 20){
            if((yearDiffPeriod) < 25) {
              diffFactor = diffFactor * Math.pow(diffFactor2001[1],(yearDiffPeriod)-20);
            }else {
              diffFactor = diffFactor * Math.pow(diffFactor2001[1],5)
	        }
          } // end if GiftD<January2003

          if((yearDiffPeriod) > 25) {
            if((yearDiffPeriod) < 30) {
              diffFactor = diffFactor * Math.pow(diffFactor2001[2],(yearDiffPeriod)-25);
	        }else {
              diffFactor = diffFactor * Math.pow(diffFactor2001[2],5);
	        }
          } // end if yearDiffPeriod > 25

          if((yearDiffPeriod) > 30) {
            diffFactor = diffFactor * Math.pow(diffFactor2001[3],(yearDiffPeriod)-30);
          } // endi if yearDiffPeriod > 30

        }else if(GiftD < July2003){

          if((yearDiffPeriod) < 20) {
            diffFactor = Math.pow(diffFactor2003[0],(yearDiffPeriod));
	      }else {
            diffFactor = Math.pow(diffFactor2003[0],20);
          }

          if((yearDiffPeriod) > 20) {
  	        diffFactor = diffFactor * Math.pow(diffFactor2003[1],(yearDiffPeriod)-20);
	      }

        } else if (GiftD < July2006){
          diffFactor = Math.pow(diffFactor2003_2[0],(yearDiffPeriod));
        } else if (GiftD < July2008){
          diffFactor = Math.pow(diffFactor2006[0],(yearDiffPeriod));
        } else if (GiftD < Feb2009){
          diffFactor = Math.pow(diffFactor2008[0],(yearDiffPeriod));		  
        } else if (GiftD < July2010) {
          diffFactor = Math.pow(diffFactor2009[0],(yearDiffPeriod));		
		} else if (GiftD < July2011) {
		  diffFactor = Math.pow(diffFactor2010[0],(yearDiffPeriod));
 		} else {
          diffFactor = Math.pow(diffFactor2011[0],(yearDiffPeriod));
        }

      } 

      diffFactor = roundOff(diffFactor,9);
      document.cres.ACGA.value = roundOff(rateACGA * diffFactor,1);   
    }else {
      diffFactor = 1;
      //document.cres.ACGA.value = roundOff(rateACGA,1);   
      document.cres.ACGA.value = rateACGA;   
    } // end if P==1 or  P==12
    //document.cres.ACGA.value = diffFactor; 
  }

} // end getACGA
function roundOff(value, precision) 
{
        value = "" + value //convert value to string
        precision = parseInt(precision);

        var whole = "" + Math.round(value * Math.pow(10, precision));

        var decPoint = whole.length - precision;

        if(decPoint != 0)
        {
                result = whole.substring(0, decPoint);
                result += ".";
                result += whole.substring(decPoint, whole.length);
        }
        else
        {
                result = whole;
        }
        return result;
}

function timeDifference(laterdate,earlierdate) {
    var difference = laterdate.getTime() - earlierdate.getTime();

    return Math.floor(difference/1000/60/60/24);
}

