// Andy Wise - Set of Java routines to calculate premiums
// AW 28 Jan 01 - Migrated into On-Line InG version 2
// AW 29 Mar 01 - Changed Buy button to Next

function calc() {
	// Step through each package type & calculate the standard rates, then ditto for Budget
	var aPackageOptions = new Array();
	var sPackage = "Long Stay";
	aPackageOptions = getDefaults(sPackage, "Standard");
	iBackPackerBase = calcVal (sPackage, aPackageOptions);
	
	sPackage = "Single";
	aPackageOptions = getDefaults(sPackage, "Standard");
	iSingleBase = calcVal (sPackage, aPackageOptions);

	sPackage = "Annual Multi Trip single";
	aPackageOptions = getDefaults(sPackage, "Standard");
	iAnnualBase_s = calcVal (sPackage, aPackageOptions);

	sPackage = "Annual Multi Trip couple";
	iAnnualBase_c = calcVal (sPackage, aPackageOptions);

	CreateOutput (iAnnualBase_s,iAnnualBase_c,iSingleBase,iBackPackerBase,"Standard");
	
	if (document.all) {
		maindocument.document.all.standardQuote.innerHTML = sOutput;
	} else {
		maindocument.document.standardQuote.document.open();
		maindocument.document.standardQuote.document.writeln(sOutput);
		maindocument.document.standardQuote.document.close();
	}
	
// Now repeat the whole thing for the Budget options

	var sPackage = "Long Stay";
	aPackageOptions = getDefaults(sPackage, "Budget");
	iBackPackerBase = calcVal (sPackage, aPackageOptions);
	
	sPackage = "Single";
	aPackageOptions = getDefaults(sPackage, "Budget");
	iSingleBase = calcVal (sPackage, aPackageOptions);

	sPackage = "Annual Multi Trip single";
	aPackageOptions = getDefaults(sPackage, "Budget");
	iAnnualBase_s = calcVal (sPackage, aPackageOptions);

	sPackage = "Annual Multi Trip couple";
	iAnnualBase_c = calcVal (sPackage, aPackageOptions);

	CreateOutput (iAnnualBase_s,iAnnualBase_c,iSingleBase,iBackPackerBase,"Budget");
	
	if (document.all) {
		maindocument.document.all.budgetQuote.innerHTML = sOutput;
	} else {
		maindocument.document.budgetQuote.document.open();
		maindocument.document.budgetQuote.document.writeln(sOutput);
		maindocument.document.budgetQuote.document.close();
	}
}

function calcVal(insPackage, PackageOptions) {
	if (document.all) {
		myForm = maindocument.document.forms["premiumCalc"];
	} else {
		myForm = maindocument.document.Quote.document.forms["premiumCalc"];
	}
	var iArea = myForm.selectX.selectedIndex;
	iArea = iArea + 1; // Moving to database has started the array at 1 not 0

	var iDuration = howLong(insPackage);
	iNewPrice = calculate (insPackage, iArea, iDuration, 1, PackageOptions);
	return iNewPrice;
}

// Get Package Defaults
// called with Insurance Package Name and variant of Standard of Budget
function getDefaults (insPackage, variant){
	var DefaultPackageOptions = new Array();
	if (variant == "Standard") {
		for (var i=0; i < AdjPackage[insPackage].length; i++) {
			if (AdjPackage[insPackage][i].IncludeInStandard ) {
				DefaultPackageOptions[i] = true;
			} else {
				DefaultPackageOptions[i] = false;
			}
		}
	} else {
		for (var i=0; i < AdjPackage[insPackage].length; i++) {
			if (AdjPackage[insPackage][i].IncludeInBudget ) {
				DefaultPackageOptions[i] = true;
			} else {
				DefaultPackageOptions[i] = false;
			}
		}
	}
	return DefaultPackageOptions;
}
// Resolve days funciton
function howLong(insPackage) {
	var iDuration;
	if (document.all) {
		myForm = maindocument.document.forms["premiumCalc"];
	} else {
		myForm = maindocument.document.Quote.document.forms["premiumCalc"];
	}
	var iY = myForm.selectY.selectedIndex;
	
//	alert ("Text is " + myForm.selectY.options[iY].text);
//	alert ("SelectedIndex value is " + iY);
//	alert ("Value is " + myForm.selectY.options[iY].value);
	if (myForm.selectY.options[iY].value == "AMT") {
		switch (insPackage) {
			case "Long Stay":
				iDuration = "-";
				break;
		   case "Single":
				iDuration = "-";
				break;
		   case "Annual Multi Trip single":
				iDuration = 0;
				break;
		   case "Annual Multi Trip couple":
				iDuration = 0;
				break;
		   default:
				iDuration = "-";
				alert ("Not sure what I am doing here - insPackage was " + insPackage);
		}
		return iDuration;		
	}
	switch (insPackage) {
		case "Long Stay":
			var aBackPackerY = packageY[1].commaarray;
			var aBackPackerY = aBackPackerY.split(",");
			for(var i=0;i < aBackPackerY.length; i++) {
				if (parseInt(aBackPackerY[i]) >= parseInt(myForm.selectY.options[iY].value)) {
					// found the correct date or the one after?
					break
				}
			}
			iDuration = i;
			break;
	   case "Single":
			var aSingleY = packageY[2].commaarray;
			var aSingleY = aSingleY.split(",");
			for(var i=0;i < aSingleY.length; i++) {	
				if (parseInt(aSingleY[i]) >= parseInt(myForm.selectY.options[iY].value)) {
					// found the correct date or the one after?
					break
				}
			}
			if (parseInt(myForm.selectY.options[iY].value) > 60) {i = "-"} // Can't sell single trip for over 60 days
			iDuration = i;
			break;
	   case "Annual Multi Trip single":
			if (parseInt(myForm.selectY.options[iY].value) <= 45) {
				iDuration = 0;  // So long as we are less than 45 days there is only 1 price
			} else {
				iDuration = "-";
			}
			break;
	   case "Annual Multi Trip couple":
			if (parseInt(myForm.selectY.options[iY].value) <= 45) {
				iDuration = 0;  // So long as we are less than 45 days there is only 1 price
			} else {
				iDuration = "-";
			}
			break;
	   default:
			iDuration = "-";
			alert ("Not sure what I am doing here - insPackage was " + insPackage);
	}
	return iDuration;
}
// Calculation function for Insure & Go 
function calculate(insPackage, area, duration, numPeople, options){
	// insPackage = the package name (backpacker, single, annualmulti, adventure)
	// area = 1 to 5 - the Insurance area {AW 7 Dec 00 - actually I think this is 0-4 and is the index from the drop down not the rate table area id - it is in fact the Xlookup index!!}
	// duration = duration - index into the duration matrix NOT the number of days
	// numPeople = number of insured people
	// options = An array indication the option numbers selected

//	alert ("Entering calc with package - " + insPackage + " area - " + area + " and duration - " + duration);
	aBasePrice = matrice[insPackage][area].rate;
	aBasePrice = aBasePrice.split(",");
	iBasePrice = aBasePrice[duration];
//	alert ("The base price for " + insPackage + " is " + iBasePrice);
	iPrice = iBasePrice * 1;   // Convert to integer otherwise addition of a "value" option fails - percentages ok strangely enough!
	// check for ApplyAsDefaults
	// alert ("There are options " + options.length);
	for (var i=0; i < options.length; i++) {
		if (options[i] == true) {
			var iIndex = AdjPackage[insPackage][i].Index;
//			alert ("Option " + i + " is " + adjustment[iIndex].value + " " + adjustment[iIndex].unit);
			if (adjustment[iIndex].unit == "percentage") {
				iPrice = (iPrice * adjustment[iIndex].value);
			} else if (adjustment[iIndex].unit == "value") {
				iPrice = (iPrice + adjustment[iIndex].value);
			}
//		alert ("Applying Option " + i + " Price is now " + iPrice);
		}
	}
	iPrice = iPrice * numPeople;
	return(iPrice);
}

function CreateOutput(AMTSingle,AMTCouple, Single,BackPacker,Type) {
	if (document.all) {
		myForm = maindocument.document.forms["premiumCalc"];
	} else {
		myForm = maindocument.document.Quote.document.forms["premiumCalc"];
	}
	
	var result = new Array();
	result[0] = Math.round(100*AMTCouple)/100;
	result[1] = Math.round(100*AMTSingle)/100;
	result[2] = Math.round(100*Single)/100;
	result[3] = Math.round(100*BackPacker)/100;
	
	// specify the package according to the correct adjustment[] array.
	// AW - 29 Jan 01 - as far as I can see this only influences the "insurancepackage" constructior (see ClientJavaScript.js), specifically aInsurancePackage.name
	var pckage = new Array();
	pckage[0] = "Annual Multi Trip couple";
	pckage[1] = "Annual Multi Trip single";
	pckage[2] = "Single";
	pckage[3] = "Long Stay";
	
	var fin = myForm.dateto.value;
	var start = myForm.datefrom.value;
	
	var buyimage = new Array();
	for (var i=0;i<result.length;i++) {
		if (isNaN(result[i])) {
			result[i] = "N/A";
			buyimage[i] = "";
		} else {
			//check decimal points
			result[i] = "£" + result[i];
			var sResult = result[i].split(".");
			//alert(sResult[1]);
			if (isNaN(sResult[1])) {
				result[i] = "" + result[i] + ".00";
			} else {
				if (sResult[1].length == 2) {
					result[i] = "" + result[i];
				} else if (sResult[1].length == 1) {
					result[i] = "" + result[i] + "0";
				}
			}
			
			resultIntoForm = "goNext('" + pckage[i] + "','" + Type +"');window.top.frames['hidden'].resutToForm('" + result[i] + "','" + packageDesc[i] + "','" + myForm.selectX.options[myForm.selectX.selectedIndex].text + "','" + start + "','" + fin + "','" + myForm.selectY.options[myForm.selectY.selectedIndex].value + "');";

			buyimage[i] = "<a href=\"javascript:" + resultIntoForm + "window.top.frames['hidden'].insurancepackage(";
			buyimage[i] += "'" + result[i] + "','" + pckage[i] + "'," + i + ",'" + packageDesc[i] + "','" + Type + "');window.top.frames['hidden'].traveldetails('" + myForm.selectX.options[myForm.selectX.selectedIndex].text + "','" + start + "','" + fin + "','" + myForm.selectY.options[myForm.selectY.selectedIndex].value + "');window.top.frames.iandgomain.window.location.href = 'steptwo.html';\" onmouseout=\"hideTip();\" onmouseover=\"showTip(3);\">";
			buyimage[i] += "<img onmouseout=\"this.src='images/NextButton.gif'\" onmouseover=\"this.style.cursor='hand';this.src='images/NextButton_o.gif';\" src='images/NextButton.gif' width='34' height='15' border='0' alt=''>";
			buyimage[i] += "</a>";
			
		}
	}

	// Output creation
	sOutput = "<table border='0' width='215'>";		
	sOutput += "<tr>";
	sOutput += "<td colspan='3' class='lilaCellb'><a href='static/annual_summary.html' onMouseOver='showTip(6)' onMouseOut='hideTip()' class='hotSpotPurple' style='font-size : 12px;'>ANNUAL MULTI-TRIP</a></td>";
//				sOutput += "<td colspan='3' class='lilaCell'>ANNUAL MULTI-TRIP</td>";
	sOutput += "</tr>";
	sOutput += "<tr>";
	sOutput += "<td class='lilaCell'>&nbsp;Couple</td>";
	sOutput += "<td class='lilaCell' align='right'>" + result[0] + "</td>";
	sOutput += "<td>" + buyimage[0] + "</td>";
	sOutput += "</tr>";
	sOutput += "<tr>";
	sOutput += "<td class='lilaCell'>&nbsp;Per Person</td>";
	sOutput += "<td class='lilaCell' align='right'>" + result[1] + "</td>";
	sOutput += "<td>" + buyimage[1] + "</td>";
	sOutput += "</tr>";
	sOutput += "<tr>";
	sOutput += "<td class='lilaCellb'><a href='static/single_summary.html' onMouseOver='showTip(7)' onMouseOut='hideTip()' class='hotSpotPurple' style='font-size : 10px;'>SINGLE TRIP</a></td>";
//				sOutput += "<td class='lilaCell'>SINGLE TRIP</td>";
	sOutput += "<td class='lilaCell' align='right'>" + result[2] + "</td>";
	sOutput += "<td>" + buyimage[2] + "</td>";
	sOutput += "</tr>";
	sOutput += "<tr>";
	sOutput += "<td class='lilaCellb'><a href='static/longstay_summary.html' onMouseOver='showTip(8)' onMouseOut='hideTip()' class='hotSpotPurple' style='font-size : 10px;'>LONG STAY</a></td>";
//				sOutput += "<td class='lilaCell'>LONG STAY</td>";
	sOutput += "<td class='lilaCell' align='right'>" + result[3] + "</td>";
				sOutput += "<td>" + buyimage[3] + "</td>";
	sOutput += "</tr>";
	sOutput += "</table>";

	//make bottom of quotegenerator visible
	if (document.all) {//IE
		window.top.frames['iandgomain'].bottomQuote.style.visibility = "visible";
	} else {//NS
		window.top.frames['iandgomain'].document.layers["bottomQuote"].visibility = "visible";	
	}	
	return sOutput;
}

function ShowOptions(sPackage, sType) {
	if (document.all) {
		myForm = maindocument.document.forms["premiumCalc"];
	} else {
		myForm = maindocument.document.content.document.forms["premiumCalc"];
	}
//	alert ("ShowOptions called with sPackage = " + sPackage + " and sType = " + sType);
// Initialise number of adults & kids - check that we are not comming back to this page (say with the back button), in which case pick up previous values
	var iNoAdults = parseInt(window.top.frames["hidden"].document.forms.vForm.noAdults.value);
	if (iNoAdults == 0) {iNoAdults = 1};
	var iNoKids = parseInt(window.top.frames["hidden"].document.forms.vForm.noKids.value);
	myForm.adults.selectedIndex = iNoAdults - 1;
	myForm.kids.selectedIndex = iNoKids;
// Initialise options - check that we are not comming back to this page (say with the back button), in which case pick up previous values
	myForm.options1.checked = window.top.frames["hidden"].document.forms.vForm.baggage.checked;
	myForm.options2.checked = window.top.frames["hidden"].document.forms.vForm.dbExcess.checked;
	myForm.options3.checked = window.top.frames["hidden"].document.forms.vForm.excessWaiver.checked;
	myForm.options4.checked = window.top.frames["hidden"].document.forms.vForm.ski.checked;
	myForm.options5.checked = window.top.frames["hidden"].document.forms.vForm.golf.checked;
	myForm.options6.checked = window.top.frames["hidden"].document.forms.vForm.business.checked;
	myForm.options3.disabled = false;
	myForm.options4.disabled = false;
	myForm.options5.disabled = false;
	myForm.options6.disabled = false;
	switch (sPackage) {
		case "Annual Multi Trip single":
			myForm.options4.checked = true;
			myForm.options4.disabled = true;
			break;
		case "Annual Multi Trip couple":
			myForm.options4.checked = true;
			myForm.options4.disabled = true;
//			myForm.adults.value = 2;
			myForm.adults.selectedIndex = 1;  // Works in Netscape & IE - .value only works in IE !!
			myForm.adults.disabled = true;
			break;
		case "Single":
			break;
		case "Long Stay":
			myForm.options3.checked = false;
			myForm.options3.disabled = true;
			myForm.options4.checked = false;
			myForm.options4.disabled = true;
			myForm.options5.checked = false;
			myForm.options5.disabled = true;
			myForm.options6.checked = false;
			myForm.options6.disabled = true;
			break;
		default:
			alert ("Should not be here, invalid package definition - " + sPackage);
	}
	calc1(); // Put up the price in the "your quote" box
}

function calc1() {
	// Do the calculations for the options when changed
	if (document.all) {
		myForm = maindocument.document.forms["premiumCalc"];
	} else {
		myForm = maindocument.document.content.document.forms["premiumCalc"];
	}
	var aPackageOptions = new Array();
	var sPackage = aInsurancePackage.name;
//	alert ("Insurance package is " + sPackage);
//	var sTmp = aInsurancePackage.desc; // Just a long version of the package name 
//	alert ("sTmp is " + sTmp);
	
	aPackageOptions[0] = myForm.options1.checked; // Inc Bagg
	aPackageOptions[1] = myForm.options2.checked; // Double Excess
	aPackageOptions[2] = myForm.options4.checked; // Ski
	aPackageOptions[3] = myForm.options3.checked; // Excess Waiver NB: Must be after Ski & same order as options declared in table PackageAdjustments
	aPackageOptions[4] = myForm.options5.checked; // Golf
	aPackageOptions[5] = myForm.options6.checked; // Business

	var sArea = window.top.frames["hidden"].document.forms["vForm"].area.value;
	switch (sArea) {
		case "United Kingdom/Channel Islands/N.Ireland":
			iArea = 1;
			break;
		case "Europe (exc. Algeria, Israel, Libya & Lebanon)":
			iArea = 2;
			break;
		case "Worldwide (exc. USA & Canada)":
			iArea = 3;
			break;
		case "Australia and New Zealand":
			iArea = 4;
			break;
		case "Worldwide (inc. USA & Canada)":
			iArea = 5;
			break;
		default:
			alert ("Invalid area definition, using WW Inc US as highest rated area");
			iArea = 5;
	}
	
	iDuration = howLong1(sPackage)
	if (sPackage == "Annual Multi Trip couple") {
		iNumAdults = 1;
	} else {
		iNumAdults = myForm.adults.options[myForm.adults.selectedIndex].value;  // Slightly contorted - but this is the only thing that works in Netscape - bless it !
	}
//	alert ("Package " + sPackage + " Area " + iArea + " Duration " + iDuration + " Adults " +  iNumAdults + " Options " + aPackageOptions);
	iCost = calculate (sPackage, iArea, iDuration, iNumAdults, aPackageOptions);
	outcost = Math.round(100*iCost)/100;
	outcost = "" + outcost;
	var sResult = outcost.split(".");
	
	if (isNaN(sResult[1])) {
		outcost = "" + outcost + ".00";
	} else {
		if (sResult[1].length == 2) {
			outcost = "" + outcost;
		} else if (sResult[1].length == 1) {
			outcost = "" + outcost + "0";
		}
	}
	if (document.all) {
		maindocument.document.all.pannelPriceDiv.innerHTML = "£" + outcost;	
	} else {
		maindocument.document.layers.pannelPriceDiv.document.open();
		maindocument.document.layers.pannelPriceDiv.document.write("£" + outcost);
		maindocument.document.layers.pannelPriceDiv.document.close();
	}
	// write calculated value to the form "upstairs" for step 3
	frmUpstairs = window.top.frames["hidden"].document.forms["vForm"].cost.value = outcost;
}

function howLong1(insPackage) {
	var iDuration;
	var frmUpstairs = window.top.frames["hidden"].document.forms["vForm"];
	if (frmUpstairs.days.value == "AMT") {
		frmUpstairs.days.value = 45;
//		aTravelDetails.days = 45;
	}
	switch (insPackage) {
		case "Long Stay":
			var aBackPackerY = packageY[1].commaarray;
			var aBackPackerY = aBackPackerY.split(",");
			for(var i=0;i < aBackPackerY.length; i++) {
				if (parseInt(aBackPackerY[i]) >= parseInt(frmUpstairs.days.value)) {
					// found the correct date or the one after?
					break
				}
			}
			iDuration = i;
			break;
	   case "Single":
			var aSingleY = packageY[2].commaarray;
			var aSingleY = aSingleY.split(",");
			for(var i=0;i < aSingleY.length; i++) {	
				if (parseInt(aSingleY[i]) >= parseInt(frmUpstairs.days.value)) {
					// found the correct date or the one after?
					break
				}
			}
			if (parseInt(frmUpstairs.days.value) > 60) {i = "-"} // Can't sell single trip for over 60 days
			iDuration = i;
			break;
	   case "Annual Multi Trip single":
			if (parseInt(frmUpstairs.days.value) <= 45) {
				iDuration = 0;  // So long as we are less than 45 days there is only 1 price
			} else {
				iDuration = "-";
			}
			break;
	   case "Annual Multi Trip couple":
			if (parseInt(frmUpstairs.days.value) <= 45) {
				iDuration = 0;  // So long as we are less than 45 days there is only 1 price
			} else {
				iDuration = "-";
			}
			break;
	   default:
			iDuration = "-";
			alert ("Not sure what I am doing here - insPackage was " + insPackage);
	}
	return iDuration;
}


