var initialLumpSumChanged = false;
var monthlySavingsChanged = false;
var interestRateChanged = false;
var termInYearsChanged = false;

function setupGrowthCalculator(){
	var initialLumpSum = $("#initialLumpSum");
	var monthlySavings = $("#monthlySavings");
	var interestRate = $("#interestRate");
	var termInYears = $("#termInYears");
	
	var buttonOL = $("#growthCalculatorButton");
	buttonOL.css("display", "none");
}


/*
function validateGCValue(value, name, minValue, valueChanged){
	var result = false;
	console.log("validate " + name + " : " + value);
	
	if(value != ""){
		if(String(parseInt(value)) == "NaN"){
			if(valueChanged){
				console.log("here 1");
				setGCValueValidityStatus(name, false);
			}
		} else {
			console.log("value (float) = " + parseFloat(value));
			if(valueChanged){
				if(String(value) == String(parseFloat(value))){
					if(parseFloat(value) >= minValue){
						console.log("here 2");
						setGCValueValidityStatus(name, true);
					} else {
						console.log("here 3");
						setGCValueValidityStatus(name, false);
					}
				} else {
					console.log("here 4");
					setGCValueValidityStatus(name, false);
				}
			}
			result = true;
		}
	} else {
		if(valueChanged){
			console.log("here 5");
			$("#" + name + "Error").css("display", "none");		
			$("#" + name + "Valid").css("display", "none");		
		}
	}
	return(result);
}
*/

function validateGCValue(value, name, regex, minValue, valueChanged){
	var result = regex.test(value); 
	
	if(result){
		//console.log("is " + parseFloat(value) + " >= " + minValue);
		result = (parseFloat(value) >= minValue);
	}
	
	if(valueChanged){
		setGCValueValidityStatus(name, result);
	}
	//console.log("validate " + name + " : " + value + " " + result);
	return(result);
}

function setGCValueValidityStatus(name, valid){
	if(valid){
		$("#" + name + "Error").css("display", "none");		
		$("#" + name + "Valid").css("display", "block");		
	} else {
		$("#" + name + "Error").css("display", "block");		
		$("#" + name + "Valid").css("display", "none");		
	}
}

function calculateGrowthCalculator(){
	var initialLumpSum = $("#initialLumpSum");
	var monthlySavings = $("#monthlySavings");
	var interestRate = $("#interestRate");
	var termInYears = $("#termInYears");

	var initialLumpSumSpan = $("#initialLumpSumSP");
	var monthlySavingsSpan = $("#monthlySavingsSP");
	var termInYearsSpan = $("#termInYearsSP");
	var totalSpan = $("#totalSP");
	var todaysMoneySpan = $("#todaysMoneySP");

	var initialLumpSumValue = initialLumpSum.val().replace(String.fromCharCode(163), "").replace(/,/g,"").replace(/ /g,"");
	var monthlySavingsValue = monthlySavings.val().replace(String.fromCharCode(163), "").replace(/,/g,"").replace(/ /g,"");
	var interestRateValue = interestRate.val().replace(/%/g, "").replace(/,/g,"").replace(/ /g,"");
	var termInYearsValue = termInYears.val();
	
	//alert(initialLumpSumValue + " " + monthlySavingsValue);
	
	var showResults = false;
	var initialLumpSumValid = false;
	var monthlySavingsValid = false;
	var interestRateValid = false;
	var termInYearsValid = false;
	
	/*	
	initialLumpSumValid = validateGCValue(initialLumpSumValue, "initialLumpSum", 0, initialLumpSumChanged);
	monthlySavingsValid = validateGCValue(monthlySavingsValue, "monthlySavings", 0, monthlySavingsChanged);
	interestRateValid = validateGCValue(interestRateValue, "interestRate", 1, interestRateChanged);
	termInYearsValid = validateGCValue(termInYearsValue, "termInYears", 1, termInYearsChanged);
	*/
	initialLumpSumValid = validateGCValue(initialLumpSumValue, "initialLumpSum", /^[0-9]+(\.[0-9]{1,2})?$/, 0, initialLumpSumChanged);
	monthlySavingsValid = validateGCValue(monthlySavingsValue, "monthlySavings", /^[0-9]+(\.[0-9]{1,2})?$/, 0, monthlySavingsChanged);
	interestRateValid = validateGCValue(interestRateValue, "interestRate", /^[0-9]+(\.[0-9]{1,2})?$/, 1, interestRateChanged);
	termInYearsValid = validateGCValue(termInYearsValue, "termInYears", /^[0-9]+$/, 1, termInYearsChanged);
	if(termInYearsValue.indexOf(".") != -1){
		termInYearsValid = false;
		setGCValueValidityStatus("termInYears", false);
	}
	
	if(initialLumpSumValid && monthlySavingsValid && interestRateValid && termInYearsValid){
		showResults = true;
				
		initialLumpSumValue = Number(initialLumpSumValue);
		monthlySavingsValue = Number(monthlySavingsValue);
		interestRateValue = Number(interestRateValue);
		interestRateValue = (interestRateValue / 100);
		termInYearsValue = Number(termInYearsValue);
				
		if(initialLumpSumValue < 0){
			showResults = false;
		}
		if(monthlySavingsValue < 0){
			showResults = false;
		}
		if(interestRateValue <= 0){
			showResults = false;
		}
		if(termInYearsValue <= 0){
			showResults = false;
		}
		
		var firstNum = Number(1 + interestRateValue);
		var spTotalValue = Math.pow(firstNum, termInYearsValue);
		spTotalValue = spTotalValue * initialLumpSumValue;
			
		var d9 = Math.pow(1+interestRateValue,1/12) - 1;
		// =(1+D9)*D6*((1+D9)^(D11*12)-1)/D9
		var mpTotalValue = ((1 + d9) * monthlySavingsValue * (Math.pow(1 + d9,termInYearsValue * 12)-1)) / d9;
				
		var totalValue = spTotalValue + mpTotalValue;
		if(String(totalValue) != "NaN"){
			totalSpan.text(String.fromCharCode(163) + totalValue.toFixed(2));
		} else {
			showResults = false;
		}
					
		//=(D14/(POWER(1.025,D11)))
		var todaysMoneyValue = totalValue / Math.pow(1.025, termInYearsValue);
		if(String(todaysMoneyValue) != "NaN"){
			todaysMoneySpan.text(String.fromCharCode(163) + todaysMoneyValue.toFixed(2) + " ");
		} else {
			showResults = false;
		}
		initialLumpSumSpan.text(String.fromCharCode(163) + initialLumpSumValue + " ");
		monthlySavingsSpan.text(String.fromCharCode(163) + monthlySavingsValue + " ");
		termInYearsSpan.text(termInYearsValue + " ");
	}
	
	if(showResults){
		$("#GCresults").css("display", "block");
		$("#GCcontent #inflationMessage").css("display", "block");		
		$("#GCcontent #enterValues").css("display", "none");
	} else {
		$("#GCresults").css("display", "none");
		$("#GCcontent #inflationMessage").css("display", "none");		
		$("#GCcontent #enterValues").css("display", "block");
	}
	var isIE6 = ($.browser.msie && $.browser.version.substr(0,1)<7);
	
	if(isIE6){
		var mainContent = $("#mainContent");
		mainContent.css("height", mainContent.outerHeight());
		//mainContent.css("background", "#FFFFFF url(/template-images/lv-rebrand-2009/layout/contentArea/mainContent/repeater.gif) repeat-y scroll right top");
			
		var container = $(".container");
		container.css("display", "block");
		
		var containerBottom = $("#containerBottom");
		containerBottom.replaceWith("<div id=\"containerBottom\"></div>");		
	}
	
	LV2009Rebrand.IE6ResizeKick();
}

var mandatoryElements = null;
var remainingMandatoryElements = 0;
var disabledButton = null;

// I don't know why this function is here, but it seems to use Prototype which has been removed
function AddMandatoryElement(elementName) {
	if(mandatoryElements == null){
		mandatoryElements = new Array();
	}
	var element = document.getElementById(elementName);
	element.mandatoryClickOccured = false;
	mandatoryElements.push(element);
	// removed cos prototype is coming out
	// Event.observe(element, 'click', function(e){ mandatoryElementClick(elementName) });
	$('#' + elementName).bind("click", function(e){ 
		mandatoryElementClick(elementName)
	});
}

function mandatoryElementClick(elementName){
	if(elementName) {
		var element = $('#' + elementName);

		if(element) {
			element.mandatoryClickOccured = true;
			remainingMandatoryElements = 0;			
			
			for(loopItem=0; loopItem < mandatoryElements.length; loopItem++) {
				fetchItem = mandatoryElements[loopItem];
				
				switch(fetchItem.tagName.toLowerCase()) {
					case 'input':
						if(!fetchItem.checked) {
							remainingMandatoryElements++;
						}
						break;
					case 'a':
						if(!fetchItem.mandatoryClickOccured) {
							remainingMandatoryElements++;
						}
						break;
				}
			}

			if(remainingMandatoryElements == 0) {			
				disabledButton.removeAttr("disabled");
				disabledButton.addClass('submit');
				disabledButton.removeClass('disabledSubmit');
			} else {
				disabledButton.attr("disabled", "disable");
				disabledButton.addClass('disabledSubmit');
				disabledButton.removeClass('submit');
			}
		}		
	}
}

function PressBackButton() {
	document.forms[0].onsubmit = function() { return true; } 
}

function DisableButtonPendingMandatoryElementsClick(submitButton){
	//debugger;
	
	var button = $('#' + submitButton);
	//var button = document.getElementById(submitButton);
	button.addClass('disabledSubmit');
	button.removeClass('submit');
	button.attr( { disabled : "disabled" } );
	disabledButton = button;	
}

var defaultSubmit;
var submitOwner;




function FiftyPlusCalculator() {
	var premiumFormElement = document.getElementById('monthlyPremium');
	if(premiumFormElement) {
		premiumFormElement.onkeypress = FiftyPlusPremiumKeyPress;
	}
	
	var sumAssuredFormElement = document.getElementById("sumAssured");
	if(sumAssuredFormElement){
		sumAssuredFormElement.onkeypress = FiftyPlusSumAssuredKeyPress;
	}  
	
	//var contentArea = document.getElementById('contentArea');
	var forms = $('.formBuilder'); //contentArea.select('.formBuilder');

	if(forms.length != 0){
		var mainForm = $('.formBuilder')[0]; //contentArea.select('.formBuilder')[0];
		defaultSubmit = mainForm.onsubmit;
		submitOwner = mainForm;
		mainForm.onsubmit = ValidateFiftyPlusAmounts;
	}
}




function ValidateFiftyPlusAmounts(){
	// do original submit
	var result = true;
	if(defaultSubmit){
		result = defaultSubmit(submitOwner);
	}
	
	if(result){
		// now we check the ranges of premium & sum assured..
		var premiumFormElement = $('#monthlyPremium');
		var sumAssuredFormElement = $("#sumAssured");
		
		var premiumAmount = premiumFormElement.val();
		var sumAssuredAmount = sumAssuredFormElement.val();
	
		if((premiumAmount == '') && (sumAssuredAmount == '')){
			alert('Please enter either a Monthly premium or Sum assured');		
			result = false;
		} else {
			if(premiumAmount != ''){
				if(!InRange(premiumAmount,5,50)){
					alert('The Monthly premium must be between ' + String.fromCharCode(163) + '5 and ' + String.fromCharCode(163) + '50');						
					result = false;
				}
			} 
			if(sumAssuredAmount != ''){
				if(!InRange(sumAssuredAmount,0,25000)){
					alert('The Sum assured cannot be more than ' + String.fromCharCode(163) + '25,000');						
					result = false;
				}
			}
		}
	}
	return(result);
}

function InRange(value,min,max){
	//alert('in range ' + value + ' ' + min + ' ' + max);
	var re = /\u00a3/gi;
	value = value.replace(re,'');
	value = value.replace(/,/g,'');
	value = value.replace(/ /g,'');
	//alert('in range 2 ' + value + ' ' + min + ' ' + max);
		
	var result = true;
	if((Number(value) < min) || (Number(value) > max)){
		result = false;	
	}
	
	return(result);
}

function FiftyPlusPremiumKeyPress(){
	var premiumFormElement = document.getElementById('monthlyPremium');
	
	if(premiumFormElement.value != ''){
		var sumAssuredFormElement = document.getElementById("sumAssured");
		if(sumAssuredFormElement){
			sumAssuredFormElement.value = '';
		}
		
		// check in correct range
	}
}

function FiftyPlusSumAssuredKeyPress(){
	var sumAssuredFormElement = document.getElementById("sumAssured");
	
	if(sumAssuredFormElement.value != ''){
		var premiumFormElement = document.getElementById('monthlyPremium');
		if(premiumFormElement){
			premiumFormElement.value = '';
		}
	}	
}

function FiftyPlusBankDetails(){
	DisableButtonPendingMandatoryElementsClick('continue_button');
	AddMandatoryElement('consent');
	AddMandatoryElement('ddGuarantee');
}

function FiftyPlusDeclarationAndConsent(){
	//DisableButtonPendingMandatoryElementsClick('continue_button');
	
	//AddMandatoryElement('consent');
	//AddMandatoryElement('ddGuarantee');
}

function FiftyPlusSummaryOfCover(){
	//DisableButtonPendingMandatoryElementsClick('continue_button');
	DisableButtonPendingMandatoryElementsClick('button_calculate');
	AddMandatoryElement('consent');
	AddMandatoryElement('agree');
	//AddMandatoryElement('application');
	//AddMandatoryElement('policySummary');
	//AddMandatoryElement('policyConditions');
}

var current50PlusSourceCode = "";


/*
AA Modified this function to use jQuery. I've removed the prototype.js
*/
function FiftyPlusCoverDetails(){
	var contentArea = $('contentArea');
	var forms = contentArea.select('.formBuilder');
	
	if(forms.length != 0){
		var mainForm = contentArea.select('.formBuilder')[0];
		defaultSubmit = mainForm.onsubmit;
		submitOwner = mainForm;
		mainForm.onsubmit = ValidateFiftyPlusCoverDetails;
	}
	
	// hide gifts div
	var giftDiv = $('#div_freeGift');
	if(giftDiv){
		//giftDiv.style.display = 'None';
		giftDiv.css("display", "None");
	}
		
	var sourceCode = $('#sourceCode');
	if(sourceCode) {
		current50PlusSourceCode = sourceCode.val();
		sourceCode.bind(
			"keyup",
			UpdateGiftDropdown
		);
	}
}

var giftListPopulated = false;

function UpdateGiftDropdown(e) {
	var value = $('#sourceCode').val();
	// Wait until they've entered 4 characters before looking up the code
	// Once the list has been populated, any change to the code causes another lookup
	if(value.length == 4 || value.length == 0 || giftListPopulated)	{
		//if(current50PlusSourceCode != value) {
	//		current50PlusSourceCode = value;
			$.get(
				'/processors/FiftyPlusProcessor/PopulateGifts?sourcecode=' + value, function(data) {
					$('#div_freeGift').html(data);
					$('#div_freeGift').css("display", "Block");
				}
			);
			giftListPopulated = true;
	//	}
	}
}

/*
function FiftyPlusCoverDetails(){
	var contentArea = $('contentArea');
	var forms = contentArea.select('.formBuilder');
	
	if(forms.length != 0){
		var mainForm = contentArea.select('.formBuilder')[0];
		defaultSubmit = mainForm.onsubmit;
		submitOwner = mainForm;
		mainForm.onsubmit = ValidateFiftyPlusCoverDetails;
	}
	
	// hide gifts div
	var giftDiv = $('div_freeGift');
	if(giftDiv){
		giftDiv.style.display = 'None';
	}
	
	var sourceCode = $('sourceCode');
	if(sourceCode){
		current50PlusSourceCode = sourceCode.value;
		sourceCode.onkeyup = function(){
			var value = $('sourceCode').value;
			if(value.length == 4){
				if(current50PlusSourceCode != value){
					// setup gift selector
					current50PlusSourceCode = value;
					
					new Ajax.Request('/processors/FiftyPlusProcessor/PopulateGifts?sourcecode=' + value,
						{    
							method:'get',
							onSuccess: function(transport){
								var response = transport.responseText || "no response text";
								
								//alert("Success! \n\n" + response);
								var giftDiv = $('div_freeGift');
								giftDiv.innerHTML = response;
								giftDiv.style.display = 'Block';
								
								//alert(response);
							},
							onFailure: function(){ alert('Something went wrong...') }
						});
				}
			}
		};
	}
}
*/


function ValidateFiftyPlusCoverDetails(){
	var result = true;
	if(defaultSubmit){
		result = defaultSubmit(submitOwner);
	}

	//if(oldFormSubmit) {
	//	result = eval(oldFormSubmit);
	//}

	return(result);
}

function DisableCoverDetailsValidation(){
	defaultSubmit = null;
	oldFormSubmit = null;
	//$("form.formBuilder").unbind("onsubmit");
}

function setPolicyNumberHiddenField(elementName){
	//alert("set policy number hidden field");
}