// Javascript functions for the buy to let calculator. 
// GRW - 11/03/05.

		//	*******************************************************************************************
		//  **************  C H A N G E    T H E     L I B O R    R A T E   H E R E *******************
		// 	*******************************************************************************************
			
			// NB* NOW DISPLAYED ON FORM AS btl SVR
			var liborRate = 5.95;
		//  THIS IS THE VARIABLE RATE
		// 	Only change the value and ensure that there is a semi-colon preceeding 
		// 	Eg. Should always look like - var liborRate = x.xx;	
		//	*******************************************************************************************
		//	*******************************************************************************************
		//	*******************************************************************************************
		
		
		//  *******************************************************************************************
		//  ********* C H A N G E    T H E    C U R R E N T     F I X E D    R A T E ******************
		//  *******************************************************************************************
			var fixedRate = 6.89;
		// THIS IS THE FIXED RATE
		// 	Only change the value and ensure that there is a semi-colon preceeding 
		// 	Eg. Should always look like -    var fixedRate = x.x;
		// 	*******************************************************************************************
		//  *******************************************************************************************
		//  *******************************************************************************************
		
		// ********************************************************************************************
		// ********************************************************************************************
		// ********************************************************************************************
			var btlBBR = 6.49;
		// ********************************************************************************************
		// ********************************************************************************************
		// ********************************************************************************************
		// ********************************************************************************************
		// ********************************************************************************************
		// ********************************************************************************************
			var fixedFee = 6.39;
		// THIS IS THE FIXED RATE with a fee of £1695
		// ********************************************************************************************
		// ********************************************************************************************
		// ********************************************************************************************
			var fixedPercentFee = 5.99;
		// THIS IS THE FIXED RATE with a fee of 2.5%
		// ********************************************************************************************
		// ********************************************************************************************
		// ********************************************************************************************
		
		var typeOfRate;
		var rateType;

		typeOfRate = 'libor';
		rateType = 'libor';
		
		// Function to reset the values in the table.
		function clearFields()
			{
				//document.calcMinRent.txtInterestRate.style.visibility = 'hidden';
				typeOfRate = 'libor';
				//document.calcMinRent.rateType[1].checked = 'true';
				
				//document.calcMaxLoan.inputRate.style.visibility = 'hidden';
				rateType = 'libor';
				//document.calcMaxLoan.typeOfRate[1].checked = 'true';
			}	
		
		// Conversion functions for the loan calculator.
		
		// Build the method that will replace white spaces to the edges of the fields to check whether the user has left 
		// any of the input fields blank.
		function strltrim() 
			{
                return this.replace(/^\s+/,'');
            }

            function strrtrim() {
                return this.replace(/\s+$/,'');
            }
            function strtrim() {
                return this.replace(/^\s+/,'').replace(/\s+$/,'');
            }

			// Declare the function processes so they can be accessed as a method.
            String.prototype.ltrim = strltrim;
            String.prototype.rtrim = strrtrim;
            String.prototype.trim = strtrim;
			
		//************************************** Validation functions. ********************************************
		
		// Function to check and see if the inputted number is a numeric value

		// This function disables the keyboard from allowing any value to be pressed other than a number.
		function numbersOnly(e) 
		{
			var arrValidChars = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57] ;
			var currentKey = document.all? window.event.keyCode:e.which;
	
			for (i in arrValidChars ) 
			{
				if (currentKey == parseInt(arrValidChars[i]))
				{
					return true;
				} 
			}
			return false;
		}

	// This function disables the keyboard from allowing any value to be pressed other than a number or a decimal.
		function numbersDecimals(e) 
		{
			var arrValidChars = [46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57] ;
			var currentKey = document.all? window.event.keyCode:e.which;
	
			for (i in arrValidChars ) 
			{
				if (currentKey == parseInt(arrValidChars[i])) 
				{
					return true;
				} 
			}
			return false;
		}

				
		// Function that will be called when the user loses focus on either of the loan amount or purchase
		// price field. This will calculate the LTV.
		
		function calculateLTV(form)
		{
		// The user has lost focus on either of the loan amount or purchase price input field. 
		// Check to see if either of the forms are blank. If they are then we can continue without
		// doing anything else. 
		
		// We will also set the value for the rental income cover rate.
			
			if(document.calcMinRent.txtLoanAmount.value.ltrim() !='' && document.calcMinRent.txtPurchasePrice.value.ltrim() !='')
			{
				// We have got this far if the user has inputted values for both the loan amount and purchase price.
				// Declare the variables that will be used.
				var loanAmount = document.calcMinRent.txtLoanAmount.value;
				var purchasePrice = document.calcMinRent.txtPurchasePrice.value;
				var ltv;
				var rentalIncome;

				// Once the input fields are validated then perform the LTV calculation and display in the LTV field.
				ltv = (loanAmount / purchasePrice) * 100 ;
								
				// Once this LTV has been calculated then we can work calculate the rental income cover rate.
				
					if (ltv <= 80.00)
						{
							rentalIncome =125;
						}
					if (ltv >= 80.01)
						{
							rentalIncome = 125;
						}

			// Check to see if the LTV value is greater than 85%. If this is the case then we cannot offer the service.
			
				if (ltv > 85)
					{
					errorMsg(2);
					return false;
					}
				// Display the LTV Rate
				document.calcMinRent.txtLtv.value = ltv.toFixed(2) + '%';
			} else {
				document.calcMinRent.txtLtv.value = '0%';
			}
		}
		
		// Function to decide the type of interest rate that is going to be used in the calculator.
		function decideRateType(form)
		
		{
			// Added by GRW.
			if (document.calcMinRent.rateType[0].checked)
			{
				//document.calcMinRent.txtInterestRate.style.visibility = 'hidden';
				typeOfRate = 'btlBBR';
			}
			if (document.calcMinRent.rateType[1].checked)
			{
				//document.calcMinRent.txtInterestRate.style.visibility = 'visible';
				typeOfRate = 'fixed';
			}

			// Added by CW.
			if (document.calcMinRent.rateType[2].checked)
			{
				//document.calcMinRent.txtInterestRate.style.visibility = 'hidden';
				typeOfRate = 'fixedPercentFee';
			}
			
			// Added by CW.
			if (document.calcMinRent.rateType[3].checked)
			{
				//document.calcMinRent.txtInterestRate.style.visibility = 'hidden';
				typeOfRate = 'fixedFee';
			}
			
			if (document.calcMinRent.rateType[4].checked)
			{
				//document.calcMinRent.txtInterestRate.style.visibility = 'hidden';
				typeOfRate = 'libor';
			}
			

			

		}
		
		// Function to display an error message if the user has inputted bad data.
		
		function errorMsg(errorNum)
		{
			var errorToDisplay;
			
			if (errorNum == 1){errorToDisplay = 'Error - Numeric values only please.';}
			if (errorNum == 2){errorToDisplay = 'Cannot Process. LTV has exceeded maximum permissable.';} // Max LTV exceeded
			if (errorNum == 3){errorToDisplay = 'Cannot Process - LTV rate is higher than the permitted value (85%).';}
			if (errorNum == 4){errorToDisplay = 'Error - You have left the rental income achievable field blank.';}
			if (errorNum == 5){errorToDisplay = 'Error - You have left the LTV field blank.';}
			if (errorNum == 6){errorToDisplay = 'Error - You have left the loan amount field blank.';}
			if (errorNum == 7){errorToDisplay = 'Error - You have left the purchase price field blank.';}

			window.alert(errorToDisplay);			
		}
		
			
		
		// This script will calculate the minimum monthly rent amount required.
		
		// function to calculate the minimum monthly rent amount required.
		// Called when the user clicks the calculate button.
		
		function calculateMinimumRent(form)
		{
		
		// Take the users input from the fields provided.
		// Declare the variables that will be used in the form and assign them values from the users input.
			
			// User inputted variables.
			var loanAmount = document.calcMinRent.txtLoanAmount.value;
			var purchasePrice = document.calcMinRent.txtPurchasePrice.value;
			
			if (loanAmount == '')
					{
						errorMsg(6);
						return false;
					}
				
				if (purchasePrice == '')
					{
						errorMsg(7);
						return false;
					}
			// Calculated Variables
			var rentalIncome;
			var requiredMinRate; 
			var ltv;
			var interestRate;
			
			// Validation calls to test the users input satisfies the criteria for calculations.
			
			// Do the calculations required.
			
				// LTV Rate
					ltv = (loanAmount / purchasePrice) * 100 ;
					
				if (typeOfRate == 'fixed') 
					{
						//var interestRate = document.calcMinRent.txtInterestRate.value;
						interestRate = fixedRate;
					}
				if (typeOfRate == 'libor')
					{
						interestRate = liborRate;
					}
				
				if (typeOfRate == "btlBBR")
					{
						interestRate = btlBBR;
					}	
					
				if (typeOfRate == "fixedFee")
					{
						interestRate = fixedFee;
					}	
				if (typeOfRate == "fixedPercentFee")
					{
						interestRate = fixedPercentFee;
					}	
				// Calculate the Rental Income Cover rate.
				// If the LTV is under 80% then the income will be set to 125. If it is more than 80.01 
				// then the value will be set to 130.
					if (ltv <= 80.00)
						{
							rentalIncome =125;
						}
					if (ltv >= 80.01)
						{
							rentalIncome = 125;
						}
			
				// Format the final calculation for the total minimum rate.
				
				requiredMinRate = loanAmount * interestRate / 100 * rentalIncome / 100 / 12;
				
				// Output the data to the screen.
					
					document.calcMinRent.txtLtv.value = ltv.toFixed(2) + '%'; 						// LTV Value
					//document.calcMinRent.txtRentalRate.value = rentalIncome; 						// Rental Rate
					document.calcMinRent.txtReqRate.value = '£' + requiredMinRate.toFixed(2); 		// Monthly repayment rate
					

		}
		
		//***************************************************************************************************
 		// Functions that will be called when the user uses the maximum loan available calculator.
		//***************************************************************************************************
		 
		function calculateMaxLoan(form)
		{
			var incomeAchieve = document.calcMaxLoan.txtRentalAchieve.value
			var LTV = document.calcMaxLoan.txtLtv.value;
			var calcRate;
			var coverRate;
			
		// Check that the fields are not left blank
		
			// income achieve
			if (incomeAchieve == '')
			{
				errorMsg(4);
				return false;
			}
		
			// LTV.
			if (document.calcMaxLoan.txtLtv.value == '')
			{
				errorMsg(5);
				return false;
			}
			
			// determine the cover rate.
			
			if (LTV > 85) 
				{
				errorMsg(3);
				return false;
				}
			else if (LTV <= 80)
				{
				coverRate = 125;
				}
			else 
				{
				coverRate = 125;
				}

			// determine the value to be used.
			
			if (typeOfRate == 'fixed')
				{
					//calcRate = document.calcMaxLoan.inputRate.value;
					calcRate = fixedRate;
				}
			
			if (typeOfRate == 'libor')
				{
					calcRate = liborRate;
				}
				
			if (typeOfRate == 'btlBBR')
				{
					calcRate = btlBBR;
				}
				
			if (typeOfRate == 'fixedFee')
				{
					calcRate = fixedFee;
				}
				
			if (typeOfRate == 'fixedPercentFee')
				{
					calcRate = fixedPercentFee;
				}
				
			// The calculation that will be used to work out the maximum loan value permitted. 
			var maxLoan;
			
			maxLoan = incomeAchieve * 12 * 100 / coverRate * 100 / calcRate;
			
			//window.alert('Max loan = ' + incomeAchieve + ' Coverrate : ' + coverRate + ' CalcRate = ' + calcRate);
			document.calcMaxLoan.txtMaxAvailable.value = '£' + Math.round(maxLoan); 	
			
		}
		
		// Edited by GRW
		
		function decideRate(form)
		{

			if (document.calcMaxLoan.typeOfRate[0].checked)
			{
				//document.calcMaxLoan.inputRate.style.visibility = 'hidden';
				typeOfRate = 'btlBBR';
			}
			if (document.calcMaxLoan.typeOfRate[1].checked)
			{
				//document.calcMaxLoan.inputRate.style.visibility = 'visible';
				typeOfRate = 'fixed';
			}
			
			if (document.calcMaxLoan.typeOfRate[2].checked)
			{
				//document.calcMaxLoan.inputRate.style.visibility = 'hidden';
				typeOfRate = 'fixedPercentFee';
			}
			if (document.calcMaxLoan.typeOfRate[3].checked)
			{
				//document.calcMaxLoan.inputRate.style.visibility = 'hidden';
				typeOfRate = 'fixedFee';
			}
			if (document.calcMaxLoan.typeOfRate[4].checked)
			{
				//document.calcMaxLoan.inputRate.style.visibility = 'hidden';
				typeOfRate = 'libor';
			}
		
		}