
function FormUpdate() {
    var form = document.NZLCalcQuote;
    CalcQuote(form);
    setDIOptions1(true);
    setDIOptions2();
}

function CalcQuote(form) {
	var lifeinsurance1 = parseFloat(form.LifeInsurance1.value);
	var critillinsurance1 = parseFloat(form.CritIllInsurance1.value);
	var accident1 = parseFloat(form.litNZALife1SumInsured.value);
	var tpdsuminsured1 = parseFloat(form.TPDSumInsured1.value);
	var incomeinsurance1 = parseFloat(form.IncomeInsurance1.value);
	var incomewaiver1 = parseFloat(form.IncomeWaiver1.value);
	var lifeinsurance2 = parseFloat(form.LifeInsurance2.value);
	var critillinsurance2 = parseFloat(form.CritIllInsurance2.value);
	var accident2 = parseFloat(form.litNZALife2SumInsured.value);
	var tpdsuminsured2 = parseFloat(form.TPDSumInsured2.value);
	var incomeinsurance2 = parseFloat(form.IncomeInsurance2.value);
	var incomewaiver2 = parseFloat(form.IncomeWaiver2.value);
	var agelife1= parseFloat(form.AgeLife1.value);
	var agelife2= parseFloat(form.AgeLife2.value);
	var ageproblem = false;
	var accel1 = form.Accelerated1.value == 'A';
	var accel2 = form.Accelerated2.value == 'A';
	var tpdaccel1 = form.TPDAccelerated1.value == 'A';
	var tpdaccel2 = form.TPDAccelerated2.value == 'A';

// alert('data ' + accel1 + accel2 + tpdaccel1 + tpdaccel2);

	if(!PriceMinMax(lifeinsurance1)) {
	  alert('The minimum for this benefit is $30,000 and the maximum is $1,000,000. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
	}

	if(!PriceMinMaxCritIll(critillinsurance1)) {
	  alert('The maximum for this benefit is $500,000. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
	}

	if(!PriceMinMaxCritIll(accident1)) {
	  alert('The maximum for this benefit is $500,000. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
	}

	if(!PriceMinMaxTPD(tpdsuminsured1)) {
	  alert('The maximum for this benefit is $500,000. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
	}

	if(!PriceMinMaxIncome(incomeinsurance1)) {
	  alert('The maximum for this benefit is $4,000/mth. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
	}

	if(!PriceMinMax(lifeinsurance2)) {
	  alert('The minimum for this benefit is $30,000 and the maximum is $1,000,000. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
	}

	if(!PriceMinMaxCritIll(critillinsurance2)) {
	  alert('The maximum for this benefit is $500,000. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
	}

	if(!PriceMinMaxCritIll(accident2)) {
	  alert('The maximum for this benefit is $500,000. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
	}

	if(!PriceMinMaxTPD(tpdsuminsured2)) {
	  alert('The maximum for this benefit is $500,000. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
	}

	if(!PriceMinMaxIncome(incomeinsurance2)) {
	  alert('The maximum for this benefit is $4,000/mth. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
	}


	if(!ValidateNum(lifeinsurance1)) {
		lifeinsurance1 = 0;
	}
	if(!ValidateNum(lifeinsurance2)) {
		lifeinsurance2 = 0;
	}
	if(!ValidateNum(critillinsurance1)) {
		critillinsurance1 = 0;
	}
	if(!ValidateNum(critillinsurance2)) {
		critillinsurance2 = 0;
	}
	if(!ValidateNum(incomeinsurance1)) {
		incomeinsurance1 = 0;
	}
	if(!ValidateNum(incomeinsurance2)) {
		incomeinsurance2 = 0;
	}
	if(!ValidateNum(incomewaiver1)) {
		incomewaiver1 = 0;
	}
	if(!ValidateNum(incomewaiver2)) {
		incomewaiver2 = 0;
	}
	if(!ValidateNum(tpdsuminsured1)) {
		tpdsuminsured1 = 0;
	}
	if(!ValidateNum(tpdsuminsured2)) {
		tpdsuminsured2 = 0;
	}
	if(!ValidateNum(accident1)) {
		accident1 = 0;
	}
	if(!ValidateNum(accident2)) {
		accident2 = 0;
	}

	if((!ValidateAge(agelife1,critillinsurance1,accident1+tpdsuminsured1+incomeinsurance1))
	  || (!ValidateAge(agelife2,critillinsurance2,accident2+tpdsuminsured2+incomeinsurance2)))
        {
	  alert('Quotes for this product can only be provided between the ages of 10 to 70 for Life, 16 to 70 for Critical Illness or 16 to 60 for TPD, Income Protection or Accident cover. For quotes outside these age ranges please contact us.');
	}

	if ((accel1 && (critillinsurance1 > lifeinsurance1)) || (accel2 && (critillinsurance2 > lifeinsurance2)))
	{
	  alert('Critical illness sum insured cannot exceed life insurance for an accelerated CI policy. Please check Life1 or Life2 values and calculate again.')
	}

	if ((tpdaccel1 && (tpdsuminsured1 > lifeinsurance1)) || (tpdaccel2 && (tpdsuminsured2 > lifeinsurance2)))
	{
	  alert('Total Permanent Disablement sum insured cannot exceed life insurance for an accelerated TPD policy. Please check Life1 or Life2 values and calculate again.')
	}

	var lifecost1 = parseFloat(form.LifeCost1.value);
	var lifecost1base = parseFloat(form.LifeCost1Base.value);
	var critillcost1= parseFloat(form.CritIllCost1.value);
	var accidentcost1= parseFloat(form.AccidentCost1.value);
	var lifecost2 = parseFloat(form.LifeCost2.value);
	var lifecost2base = parseFloat(form.LifeCost2Base.value);
	var critillcost2= parseFloat(form.CritIllCost2.value);
	var accidentcost2= parseFloat(form.AccidentCost2.value);
	var tpdinsurance1 = parseFloat(form.TPDInsurance1.value);
	var tpdinsurance2 = parseFloat(form.TPDInsurance2.value);

	if(!ValidateNum(lifecost1)) {
		lifecost1 = 0;
	}

	if(!ValidateNum(lifecost1base)) {
		lifecost1base = 0;
	}

	if(!ValidateNum(critillcost1)) {
		critillcost1 = 0;
	}

	if(!ValidateNum(accidentcost1)) {
		accidentcost1 = 0;
	}

	if(!ValidateNum(tpdinsurance1)) {
		tpdinsurance1 = 0;
	}
	
	if(!ValidateNum(lifecost2)) {
		lifecost2 = 0;
	}

	if(!ValidateNum(lifecost2base)) {
		lifecost2base = 0;
	}

	if(!ValidateNum(critillcost2)) {
		critillcost2 = 0;
	}

	if(!ValidateNum(accidentcost2)) {
		accidentcost2 = 0;
	}

	if(!ValidateNum(tpdinsurance2)) {
		tpdinsurance2 = 0;
	}

	var sumlife1 = lifecost1+critillcost1+accidentcost1+tpdinsurance1+incomeinsurance1+incomewaiver1;
	form.SumLife1.value = FmtPrice(sumlife1);
	form.LifeCost1.value = FmtPrice(lifecost1);
	form.CritIllCost1.value = FmtPrice(critillcost1);
	form.AccidentCost1.value = FmtPrice(accidentcost1);
	form.TPDInsurance1.value = FmtPrice(tpdinsurance1);
	form.IncomeInsurance1.value = FmtPrice(incomeinsurance1);
	form.IncomeWaiver1.value = FmtPrice(incomewaiver1);

	var sumlife2 = lifecost2+critillcost2+accidentcost2+tpdinsurance2+incomeinsurance2+incomewaiver2;
	form.SumLife2.value = FmtPrice(sumlife2);
	form.LifeCost2.value = FmtPrice(lifecost2);
	form.CritIllCost2.value = FmtPrice(critillcost2);
	form.AccidentCost2.value = FmtPrice(accidentcost2);
	form.TPDInsurance2.value = FmtPrice(tpdinsurance2);
	form.IncomeInsurance2.value = FmtPrice(incomeinsurance2);
	form.IncomeWaiver2.value = FmtPrice(incomewaiver2);

	form.SumLife2.value = FmtPrice(sumlife2);

// If modifying 5.81 below, check also other places in this file, in CSV app, in whteko
// and in javascript.whtm which makes quickcalclife.js!
	var sumtotal = sumlife1+sumlife2 + 5.81;

	var CQCostYear = sumtotal*12;
	var CQfivePercent = CQCostYear/100*4.75;
	var sumtotalyear = CQCostYear-CQfivePercent;

	var sumtotalfortnightly = CQCostYear/26;
	
	if(!ValidateTotal(sumtotal)) {
	  if(sumtotal > 5.81) {
  		if(sumtotal < 15) {
                       alert('The minimum total premium is $15 per month. (NZLife recommends you consider increasing cover to optimise your premium cost).');
		}
	  }
	}

	form.TotalQuote.value = FmtPrice(sumtotal);
	form.TotalQuoteYear.value = FmtPrice(sumtotalyear);
	form.TotalQuoteFortNightly.value = FmtPrice(sumtotalfortnightly);
}

function FormUpdateIncome(Startup) {
 var form = document.NZLCalcQuote;
 var agelife1= parseFloat(form.AgeLife1.value);
 var incomeinsurance1 = parseFloat(form.IncomeInsurance1.value);
 var incomewaiver1 = parseFloat(form.IncomeWaiver1.value);

if (Startup) {
 var incomeprotection = parseFloat(form.DISumInsured1.value);
 if(!PriceMinMaxStartup(incomeprotection)) {
   alert('This benefit must be between $1,000/mth and $9,000/mth. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
 }
} else if(!PriceMinMaxIncome(incomeinsurance1)) {
   alert('The maximum for this benefit is $4,000/mth. Please remove any commas or currency dollar signs. If you require sums outside these limits visit www.adviser.co.nz and a personalised quote will be emailed to you.');
}

 if(!ValidateNum(incomeinsurance1)) {
	incomeinsurance1 = 0;
 } 
 if(!ValidateNum(incomewaiver1)) {
	incomewaiver1 = 0;
 }

 if((!ValidateAge(agelife1,0,incomeinsurance1)))
 {
  alert('Quotes for this product can only be provided between the ages of 10 to 70 for Life, 16 to 70 for Critical Illness or 16 to 60 for TPD, Income Protection or Accident cover. For quotes outside these age ranges please contact us.');
 }

 var sumlife1 = incomeinsurance1+incomewaiver1;
 form.SumLife1.value = FmtPrice(sumlife1);
 form.IncomeInsurance1.value = FmtPrice(incomeinsurance1);
 form.IncomeWaiver1.value = FmtPrice(incomewaiver1);

 var sumtotal = sumlife1;
// NO policy fee added for Startup quotes - change fee below if changed elsewhere!

 if (!Startup) {
   sumtotal = sumtotal + 5.81;
 }

 var CQCostYear = sumtotal*12;
 var CQfivePercent = CQCostYear/100*4.75;
 var sumtotalyear = CQCostYear-CQfivePercent;

 var sumtotalfortnightly = CQCostYear/26;
	
 if(!ValidateTotal(sumtotal)) {
   if(sumtotal < 15) {
         alert('The minimum total premium is $15 per month. (NZLife recommends you consider increasing cover to optimise your premium cost).');
   }	
 }

 form.TotalQuote.value = FmtPrice(sumtotal);
 form.TotalQuoteYear.value = FmtPrice(sumtotalyear);
 form.TotalQuoteFortNightly.value = FmtPrice(sumtotalfortnightly);
}

function PriceMinMax(checkVal) {

	returnVal = parseFloat(checkVal);
	
	if(returnVal == 0) return true;	
	else if(returnVal < 30000) return false;
	else if(returnVal > 1000000) return false;
	else return true;
}

function PriceMinMaxCritIll(checkVal) {

	returnVal = parseFloat(checkVal);

	if(returnVal > 500000) return false;
	else return true;
}

function PriceMinMaxTPD(checkVal) {

	returnVal = parseFloat(checkVal);

	if(returnVal > 500000) return false;
	else return true;
}

function PriceMinMaxIncome(checkVal) {

	returnVal = parseFloat(checkVal);

	if(returnVal > 4000) return false;
	else return true;
}

function PriceMinMaxStartup(checkVal) {

	returnVal = parseFloat(checkVal);
	if(returnVal > 9000) return false;
	else if(returnVal < 1000) return false;
	else return true;
}


function ValidateTotal(checkVal) {

	returnVal = parseFloat(checkVal);

	if(returnVal > 0) return false;
	else return true;
}

function FmtPrice(result) {
                    result = ConvNumber(result, 2, ".");
                    return result;
}

function ConvNumber(expr, decplaces, point) {

	var str = "" + Math.round(eval(expr) * Math.pow(10,decplaces));
	while (str.length <= decplaces) {
		str = "0" + str;
	}
	var decpoint = str.length - decplaces;
	return (str.substring(0,decpoint) + point + str.substring(decpoint,str.length));
}

function ValidateNum(checkVal) {

	returnVal = parseFloat(checkVal);

	if(isNaN(returnVal)) return false;
	else if(returnVal < 0) return false;
	else return true;
}

function ValidateAge(checkVal,critincomeval,othersval) {

	returnVal = parseFloat(checkVal);

// alert(' data ' + checkVal + ' ' + critincomeval + ' ' + othersval);
	if(returnVal < 10) return false;
	else if(returnVal > 70) return false;
	else if ((returnVal < 16) && (critincomeval + othersval > 0)) return false;
	else if ((returnVal > 60) && (othersval > 0)) return false;
	else return true;
}

function FmtPrice(result) {
                    result = ConvNumber(result, 2, ".");
                    return result;
}

function ConvNumber(expr, decplaces, point) {

	var str = "" + Math.round(eval(expr) * Math.pow(10,decplaces));
	while (str.length <= decplaces) {
		str = "0" + str;
	}
	var decpoint = str.length - decplaces;
	return (str.substring(0,decpoint) + point + str.substring(decpoint,str.length));
}

function ValidateNum(checkVal) {

	returnVal = parseFloat(checkVal);

	if(isNaN(returnVal)) return false;
	else if(returnVal < 0) return false;
	else return true;
}

function changeDisplay( elementId, setTo ) {
  var theElement;
  if( document.getElementById ) {
    //DOM
    theElement = document.getElementById( elementId );
  } else if( document.all ) {
    //Proprietary DOM
    theElement = document.all[ elementId ];
  }
  if( !theElement ) {
    /* The page has not loaded, or the browser claims to
    support document.getElementById or document.all but
    cannot actually use either */
    return;
  }
  //Reference the style ...
  if( theElement.style ) { theElement = theElement.style; }
  if( typeof( theElement.display ) == 'undefined' ) {
    //The browser does not allow us to change the display style
    //Alert something sensible (not what I have here ...)
    window.alert( 'Your browser does not support this' );
    return;
  }
  //Change the display style
  theElement.display = setTo;
}

function setDIOptions1(CheckSumInsured) {


var form = document.NZLCalcQuote;

// form.debug1.value = "";

var chosen = form.DICoverRequired1.options[form.DICoverRequired1.selectedIndex].value;
var waitdropdown = form.DIWaitingPeriod1;
var payperiod = form.DIPayoutPeriod1;
var suminsured = form.DISumInsured1;
var grossIncome = parseFloat(form.DIAnnualIncome1.value);

setDIOptions(CheckSumInsured,chosen,form,form.DIWaitingPeriod1,payperiod,suminsured,grossIncome,1, form.DIOccupation1.options[form.DIOccupation1.selectedIndex].value);

}

function setDIOptions2() {

var form = document.NZLCalcQuote;
var chosen = form.DICoverRequired2.options[form.DICoverRequired2.selectedIndex].value;
var waitdropdown = form.DIWaitingPeriod2;
var payperiod = form.DIPayoutPeriod2;
var suminsured = form.DISumInsured2;
var grossIncome = parseFloat(form.DIAnnualIncome2.value);

setDIOptions(false,chosen,form,waitdropdown,payperiod,suminsured,grossIncome, 2,form.DIOccupation2.options[form.DIOccupation2.selectedIndex].value);

}


function setDIOptions(CheckSumInsured,chosen,form,waitdropdown,payperiod,suminsured,grossIncome,which,occ) {
var wdval = waitdropdown.value; // waitdropdown.selectedindex
var ppval = payperiod.value;
// form.debug1.value = form.debug1.value + chosen + "/" + wdval + '-'+ppval + ', ';

waitdropdown.options.length = 0;
payperiod.options.length = 0;

if (chosen == "0") { // Essential
  waitdropdown.options[waitdropdown.options.length] = new Option('8 weeks','8');
  payperiod.options[payperiod.options.length] = new Option('5 years','5');
  payperiod.options[payperiod.options.length] = new Option('To age 65','65');
  changeDisplay("DISumInsuredEditBox" + which,"inline");
  changeDisplay("DISumInsuredDropdown" + which,"none");
}
else if (chosen == "3") { // Startup
  waitdropdown.options[waitdropdown.options.length] = new Option('4 weeks','4');
  waitdropdown.options[waitdropdown.options.length] = new Option('8 weeks','8');
  waitdropdown.options[waitdropdown.options.length] = new Option('13 weeks','13');
//   changeDisplay("DISumInsuredEditBox" + which,"none");
//  changeDisplay("DISumInsuredDropdown" + which,"inline");
  payperiod.options[payperiod.options.length] = new Option('6 months','6');
  payperiod.options[payperiod.options.length] = new Option('12 months','1');
  payperiod.options[payperiod.options.length] = new Option('24 months','2');
}
else { // Comprehensive*
  waitdropdown.options[waitdropdown.options.length] = new Option('2 weeks','2');
  waitdropdown.options[waitdropdown.options.length] = new Option('4 weeks','4');
  waitdropdown.options[waitdropdown.options.length] = new Option('8 weeks','8');
  waitdropdown.options[waitdropdown.options.length] = new Option('13 weeks','13');
  waitdropdown.options[waitdropdown.options.length] = new Option('6 months','26');
  waitdropdown.options[waitdropdown.options.length] = new Option('1 year','52');
  waitdropdown.options[waitdropdown.options.length] = new Option('2 years','104');
  payperiod.options[payperiod.options.length] = new Option('1 year','1');
  payperiod.options[payperiod.options.length] = new Option('2 years','2');
  payperiod.options[payperiod.options.length] = new Option('5 years','5');
  payperiod.options[payperiod.options.length] = new Option('To age 65','65');
  payperiod.options[payperiod.options.length] = new Option('To age 70','70');
  changeDisplay("DISumInsuredEditBox" + which,"inline");
  changeDisplay("DISumInsuredDropdown" + which,"none");
}

// try to reestablish correct dropdown settings, if still valid:
waitdropdown.value = wdval;
payperiod.value = ppval;

if (CheckSumInsured) {
  CheckDISumInsured(suminsured,grossIncome,chosen,occ);
}

}


function checkDISumInsured1() {

var form = document.NZLCalcQuote;
var chosen = form.DICoverRequired1.options[form.DICoverRequired1.selectedIndex].value;
var suminsured = form.DISumInsured1;
var grossIncome = parseFloat(form.DIAnnualIncome1.value);

CheckDISumInsured(suminsured,grossIncome,chosen,form.DIOccupation1.options[form.DIOccupation1.selectedIndex].value);

}

function checkDISumInsured2() {

var form = document.NZLCalcQuote;
var chosen = form.DICoverRequired2.options[form.DICoverRequired2.selectedIndex].value;
var suminsured = form.DISumInsured2;
var grossIncome = parseFloat(form.DIAnnualIncome2.value);

CheckDISumInsured(suminsured,grossIncome,chosen,form.DIOccupation2.options[form.DIOccupation2.selectedIndex].value);

}


function CheckDISumInsured(suminsured,grossIncome,chosen,occ) {

var incomeProtection = parseFloat(suminsured.value);
var monthlyIncome = grossIncome/12;
var fiftyfivePercent = FmtPrice(monthlyIncome*.55);
var seventyfivePercent = FmtPrice(monthlyIncome*.75);

if (chosen <  "2") { // the two Indemnity plans- essential and Comprehensive
// alert(chosen + ' - ' + occ + ' - ' + incomeProtection);
  if (incomeProtection > seventyfivePercent) {
  alert('Maximum Income Protection is 75% of gross income.\nPlease enter a value of ' + seventyfivePercent + ' or less');
  suminsured.value = seventyfivePercent;
  } else if (( chosen == "0") && (occ == "5") && (incomeProtection > 2500) ) {
    alert('Maximum Essential Disability protection is $2500/month if you are not employed.\nPlease enter a value of $2500 or less');
    suminsured.value = 2500;
  }

} else { // the two "Agreed" plans - Comprehensive Agreed and Startup
  if (chosen == '3') { // Startip
    if ((incomeProtection < 1000) || (incomeProtection > 9000)) {
      alert('Income Protection must be between $1,000 and $9,000. Omit dollar sign and commas when entering a value.');
      suminsured.value = 1000;
    }
  }

  if (incomeProtection > fiftyfivePercent) {
    alert('Maximum Income Protection is 55% of gross income\nPlease enter a value of ' + fiftyfivePercent + ' or less');
   suminsured.value = fiftyfivePercent;
  }

}
}
