/*
 * ING Homeloan Controllers v2.0
 * - new LVRs
 */

$(document).ready(function () {
	var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
	if (isIOS) {
		$('html').addClass('iOS');
	}
});

// Inject Homeloan-App into ING-App
angular.module("Homeloan-App", ['ING-App', 'slickCarousel', 'dynamicNumber']);

// v1.3 Debounce - https://stackoverflow.com/questions/29771011/angularjs-watch-with-debounce
// NOTE: keep this for future use
angular.module("Homeloan-App").factory('debounce', ['$timeout','$q', function($timeout, $q) {
	return function debounce(func, wait, immediate) {
		var timeout;
		var deferred = $q.defer();
		return function() {
			var context = this, args = arguments;
			var later = function() {
				timeout = null;
				if(!immediate) {
					deferred.resolve(func.apply(context, args));
					deferred = $q.defer();
				}
			};
			var callNow = immediate && !timeout;
			if ( timeout ) {
				$timeout.cancel(timeout);
			}
			timeout = $timeout(later, wait);
			if (callNow) {
				deferred.resolve(func.apply(context,args));
				deferred = $q.defer();
			}
			return deferred.promise;
		};
	};
}]);

angular.module('Homeloan-App').controller('HomeloanController', ["$scope", "$timeout", function ($scope, $timeout) {

	$scope.mainInfo = {
		readyToStart: false,
		activePage: 0,  // only using initializing
		tabInfos: [
			{ title: 'Tools & calculators', icon: '/svgs/homeloan-symbols.svg#homeloan-svg-calculator' },
			{ title: 'How-to guides, hints & tips', icon: '/svgs/homeloan-symbols.svg#homeloan-svg-question' }
		],
		getInterestRateByCode: function (code) {
			return _getInterestRate(code);
		},
		startCompare: function () {
			$('[data-toggle="tab"][href="#main-tab-0"]').trigger('click');
			$timeout(function () {
				$scope.mainInfo.refineRepayment();
			});
		},
		getIRString: function (number) {
			return Number(number).formatMoney(2, '.', ',');
		},
		isTableOpen: false,
		goToComparison: function() {
			$scope.mainInfo.updateActivePage(0);
			$scope.mainInfo._scrollUp();
		},
		updateActivePage: function(newPageIndex) {
			$scope.mainInfo.activePage = newPageIndex;
		},
		_scrollUp: function() {
			var homeloanContent = document.querySelector('.homeloan-content'),
				homeloanContentRect = homeloanContent.getBoundingClientRect(),
				topMargin = 100, // 60 for the sticky header + 40 extra
				targetScrollPosition = homeloanContentRect.top + window.scrollY - topMargin;

			window.scrollTo(0, targetScrollPosition);
		}
	};

	var _interestRateInfo = undefined;

	$scope.init = function () {
		//console.log('HomeloanController initialized.');
		var info = $('#HomeloanController').data('interestRateInfo');
		if (typeof info !== 'undefined') {
			_saveInterestRates(info);
		}
	};

	// communicate with InterestRateManager.js
	$scope.notifyInterestRateInfo = function (info) {
		_saveInterestRates(info);
	};

	var _saveInterestRates = function (info) {
		_interestRateInfo = info;
		//console.log('Ready to use InterestRateInfo');
		_startApp();
	};

	var _getInterestRate = function (code) {
		var rate = null;
		if (angular.isDefined(_interestRateInfo)) {
			angular.forEach(_interestRateInfo.InterestRates, function (info, index) {
				if (info.RateCode === code) {
					rate = info.Rate;
				}
			});
		}
		return rate;
	};

	var _startApp = function () {
		$timeout(function () {
			$scope.mainInfo.updateCalculator();
			$scope.mainInfo.readyToStart = true;

			// for tab header svgs on IE
			svg4everybody();
		});
	};
}]);


// FIRST TAB CONTROLLER
// ----------------------------------------------
angular.module('Homeloan-App').controller('HomeloanCompareController', ["$scope", "$timeout", "$uibModal", "$sce", function ($scope, $timeout, $uibModal, $sce) {
	// v2.0 - CACHE
	// 'FRL_OO_P&I_7080' => {code1: 9.99, code2: 9.99} 
	var _RATES_CACHE = [];

	// v2.0 - FRL display year
	var _compareYear = 3;

	// PAGE INFO
	$scope.pageInfo = {
		title: 'Add your basics to compare home loans:',
		repaymentOptionsCollapsed: true,
		borrowingInputShown: false,
		toggleRepaymentOptions: function () {
			$scope.pageInfo.repaymentOptionsCollapsed = !$scope.pageInfo.repaymentOptionsCollapsed;
			$timeout(function () {
				$scope.pageInfo.borrowingInputShown = !$scope.pageInfo.borrowingInputShown;
			}, 500);

			// animation for refine repayment options
			var offset = $('.module-tab-content').offset().top - 60.0;
			$('body, html').animate({ 'scrollTop': offset + 'px' }, 500);
		},
		refineRepayment: function () {
			if (mediaQuery == media_xs) {
				$scope.pageInfo.openModalMobileCalculator();
			}
			else {
				if ($scope.pageInfo.repaymentOptionsCollapsed) {
					$scope.pageInfo.repaymentOptionsCollapsed = !$scope.pageInfo.repaymentOptionsCollapsed;
					$timeout(function () {
						$scope.pageInfo.borrowingInputShown = !$scope.pageInfo.borrowingInputShown;
					}, 500);
				}
				// animation for refine repayment options
				var offset = $('.module-tab-content').offset().top - 60.0;
				$('body, html').animate({ 'scrollTop': offset + 'px' }, 500);
			}
		},
		// MOBILE MODAL CALCULATOR
		openModalMobileCalculator: function () {
			var modal = $uibModal.open({
				animation: true,
				templateUrl: 'modalMobileCalculatorTemplate.html',
				controller: 'ModalMobileCalculatorController',
				windowClass: 'homeloan-modal-style',
				resolve: {
					calcOptions: function () {
						return $scope.calcOptions;
					}
				}
			});
			modal.result.then(function (calcOptions) {
				$scope.calcOptions = calcOptions;
			}, function () {
				//console.log('Modal dismissed at: ' + new Date());
			});
		},
		// MOBILE MODAL TABLE
		openModalMobileFixedRateTable: function () {
			var modal = $uibModal.open({
				animation: true,
				templateUrl: 'modalMobileFixedRateTableTemplate.html',
				controller: 'ModalMobileFixedRateTableController',
				windowClass: 'homeloan-modal-style',
				resolve: {
					fixedRateTableInfo: function () {
						return $scope.fixedRateTableInfo;
					},
					mainInfo: function () {
						return $scope.mainInfo;
					},
				}
			});
		},
		// MODAL GENERIC INFORMATION
		openModalGenericInformation: function (index) {
			var templateUrl = undefined;
			var title = $scope.cardInfos[index].title;
			if (title === 'Mortgage Simplifier') {
				templateUrl = 'modalMortgageSimplifierInformationTemplate.html';
			} else if (title === 'Orange Advantage') {
				templateUrl = 'modalOrangeAdvantageInformationTemplate.html';
			} else if (title === 'Fixed Rate Loan') {
				if ($scope.calcOptions.optionPurpose.selected == 0) {
					templateUrl = 'modalFixedRateLiveInInformationTemplate.html';
				}
				else if ($scope.calcOptions.optionPurpose.selected == 1) {
					templateUrl = 'modalFixedRateInvestInInformationTemplate.html';
				}
			}

			if (angular.isDefined(templateUrl)) {
				$uibModal.open({
					animation: true,
					templateUrl: templateUrl,
					controller: 'ModalGenericController',
					windowClass: 'blue-modal-style',
				});
			}
		},
		// SLICK CAROUSEL
		slickConfig: {
			infinite: false,
			slidesToShow: 1,
			slidesToScroll: 1,
			arrows: true,
			prevArrow: '<button type="button" class="slick-prev"><span class="icon-font icon-arrow-left"></span></button>',
			nextArrow: '<button type="button" class="slick-next"><span class="icon-font icon-arrow-right"></span></button>',
			// event: {
			//   init: function(event, slick) {
			//     //console.log('slick initialized...');
			//   }
			// }
		}
	};
	// register refineRepayment method on root controller in order to call it from outside of this controller
	$scope.mainInfo.refineRepayment = function () {
		$scope.pageInfo.refineRepayment();
	};
	$scope.mainInfo.selectFixedRate = function (tableIndex, rowIndex) {
		//console.log(tableIndex + ', ' + rowIndex);
		$scope.fixedRateTableInfo.updateFixedRateCardInfo(tableIndex, rowIndex);
		$scope.mainInfo.isTableOpen = false;
	};

	// CALCULATOR OPTIONS
	$scope.calcOptions = {
		optionPurpose: {
			title: 'Purpose:',
			menus: [
			  { name: 'To live in', value: undefined },
			  { name: 'To invest in', value: undefined },
			],
			selected: 0,
		},
		optionBorrowing: {
			title: 'Total borrowings:',
			menus: [
				{ name: '< $150K', nameXs: '< $150K', value: '100000', threshold: 150000 },
				{ name: '$150K - <br/>$500K', nameXs: '$150K - $500K', value: '300000', threshold: 500000, doubleline: true },
				{ name: '> $500K', nameXs: '$500K - $1Million', value: '500000', threshold: 1000000, doubleline: true },
				{ name: '> $1Million', nameXs: '> $1Million', value: '1000000', threshold: Number.MAX_VALUE },
			],
			selected: 2,
			value: '0',
			isFromInput: false,
			isFromRadio: true,
			minValue: 150000,
			errorMessage: 'Min total borrowings amount is $150,000',
			showError: false,
			depositThreshold: 150000,
		},
		optionDeposit: {
			title: 'LVR:',
			menus: [
				{ name: '60% or less', value: 0, hide: false }, // v2.0 - 0
				{ name: '60.01%-70%', value: 1, hide: false }, // v2.0 - 1
				{ name: '70.01%-80%', value: 2, hide: false }, // v2.0 - 2
				{ name: '80.01%-90%', value: 3, hide: false }, // v2.0 - 3
				{ name: '90.01%-95%', value: 4, hide: false }, // v2.0 - 4
			],
			selected: { name: '60% or less', value: 0, hide: false },
			value: undefined,
			// allow20only: false, // v1.4 - replaced by hide above
		},
		optionRepayment: {
			title: 'Repayment type:',
			menus: [
				{ name: 'Principal & <br/>interest', value: '', doubleline: true },
				{ name: 'Interest only', value: 'interest' },
			],
			selected: 0,
		},
		optionFrequency: {
			title: 'Frequency:',
			menus: [
				{ name: 'Fortnightly', value: 26 },
				{ name: 'Monthly', value: 12 },
			],
			selected: { name: 'Monthly', value: 12 },
			selectedIndex: 1, // MARK: only for mobile!!
		},
		optionLoanTerm: {
			title: 'Loan term:',
			menus: [
				{ name: '5 years', value: 5 },
				{ name: '10 years', value: 10 },
				{ name: '15 years', value: 15 },
				{ name: '20 years', value: 20 },
				{ name: '25 years', value: 25 },
				{ name: '30 years', value: 30 },
			],
			selected: { name: '30 years', value: 30 },
		},
		forCard: {
			frequency: '[FREQUENCY]',
			description: '[DESCRIPTION]',
			descriptionFixedRate: '[DESCRIPTION-FIXEDRATE]',
		},
	};

	// CARD INFO
	$scope.cardInfos = [
		{
			title: 'Mortgage Simplifier',
			linkedUrl: '/home-loans/mortgage-simplifier.html',
			description: 'Want no annual fee?',
			interestInfo1: {
				name: 'Variable rate',
			},
			interestInfo2: {
				name: 'Comparison rate <a href="" tabindex="0" aria-label="information-icon"  class="btn-symbol color-dark-gray" uib-popover-template="\'popoverSmallCompTemplate.html\'" popover-trigger="outsideClick" popover-class="homeloan-popover-small" popover-append-to-body="true" type="button"><span class="icon-font icon-instruction"></span></a>',
			},
			repaymentValue: undefined,
			disclaimer: 'Our lowest variable rate when borrowing $500,000 <br class="hidden-xs hidden-sm hidden-md" />over 30 years paying interest & principal.',
			features: [
				{
					icon: '',
					content: 'Unlimited additional repayments'
				},
				{
					icon: '',
					content: 'No interest offset'
				},
				{
					icon: '',
					content: 'Redraw facility'
				},
				{
					icon: '',
					content: 'Pay off your home loan and save at the same time with <a href="/everyday-banking/everyday-round-up.html?pid=vis:hlpp:table:hleru">Everyday Round Up</a>'
				}
			],
			featuresOther: [
				{
					icon: '',
					content: 'No annual fee'
				},
				{
					icon: '',
					content: 'No account-keeping fees'
				},
				{
					icon: '',
					content: 'Pay as you go servicing fees for switches or variations'
				},
				{
					icon: '',
					content: '<a target="_blank" href="https://www.ing.com.au/assets/pdf/INGD_IM0591112_PreSettlementFeesandCharges.pdf">Pre-settlement fees and charges</a>'
				},
				{
					icon: '',
					content: '<a target="_blank" href="https://www.ing.com.au/assets/pdf/INGD_IM227_Post_Settlement_Fees_0715_WEB.pdf">Post-settlement fees and charges</a>'
				}
			],
			alertInfo: {
				collapsed: true,
				content: 'You could save $59,612.37 and pay off your loan 4 years and 4 months quicker',
			},
		},
		{
			title: 'Orange Advantage',
			linkedUrl: '/home-loans/orange-advantage.html',
			description: 'Want access to an offset?',
			interestInfo1: {
				name: 'Variable rate',
			},
			interestInfo2: {
				name: 'Comparison rate <a href="" tabindex="0" aria-label="information-icon"  class="btn-symbol color-dark-gray" uib-popover-template="\'popoverSmallCompTemplate.html\'" popover-trigger="outsideClick" popover-class="homeloan-popover-small" popover-append-to-body="true" type="button"><span class="icon-font icon-instruction"></span></a>',
			},
			repaymentValue: undefined,
			disclaimer: 'Our lowest variable rate when borrowing $500,000 <br class="hidden-xs hidden-sm hidden-md" />over 30 years paying interest & principal.',
			features: [
				{
					icon: '',
					content: '100% interest offset when combined with Orange Everyday'
				},
				{
					icon: '',
					content: 'Unlimited additional repayments'
				},
				{
					icon: '',
					content: 'Redraw facility'
				},
				{
					icon: '',
					content: 'Pay off your home loan and save at the same time with <a href="/everyday-banking/everyday-round-up.html?pid=vis:hlpp:table:hleru">Everyday Round Up</a>'
				},
				{
					icon: '',
					content: '<a target="_blank" href="https://www.ing.com.au/assets/pdf/INGD_IM0591112_PreSettlementFeesandCharges.pdf">Pre-settlement fees and charges</a>'
				},
				{
					icon: '',
					content: '<a target="_blank" href="https://www.ing.com.au/assets/pdf/INGD_IM227_Post_Settlement_Fees_0715_WEB.pdf">Post-settlement fees and charges</a>'
				}
			],
			featuresOther: [
				{
					icon: '',
					content: 'No monthly, switch or variations fees'
				},
				{
					icon: '',
					content: 'Low $299 annual fee'
				},
				{
					icon: '',
					content: 'Discharge and other fees may still apply'
				},
				{
					icon: '',
					content: '<a target="_blank" href="https://www.ing.com.au/assets/pdf/INGD_IM0591112_PreSettlementFeesandCharges.pdf">Pre-settlement fees and charges</a>'
				},
				{
					icon: '',
					content: '<a target="_blank" href="https://www.ing.com.au/assets/pdf/INGD_IM227_Post_Settlement_Fees_0715_WEB.pdf">Post-settlement fees and charges</a>'
				}
			],
			alertInfo: {
				collapsed: true,
				content: 'You could save $59,612.37 and pay off your loan 4 years and 4 months quicker',
			},
		},
		{
			title: 'Fixed Rate Loan',
			linkedUrl: '/home-loans/fixed-rate-home-loan.html',
			description: 'Looking for repayment and rate certainty?',
			interestInfo1: {
				name: '',
				showTable: false, // v1.4b
			},
			interestInfo2: {
				name: 'Comparison rate <a href="" tabindex="0" aria-label="information-icon"  class="btn-symbol color-dark-gray" uib-popover-template="\'popoverSmallCompTemplate.html\'" popover-trigger="outsideClick" popover-class="homeloan-popover-small" popover-append-to-body="true" type="button"><span class="icon-font icon-instruction"></span></a>',
			},
			specialOffer: 4,
			repaymentValue: undefined,
			disclaimer: 'Our lowest fixed rate during a fixed rate period when <br class="hidden-xs hidden-sm hidden-md" />borrowing $500,000 over 30 years paying interest & principal.',
			features: [
				{
					icon: '',
					content: 'Rate and repayment certainty for up to 5 years'
				},
				{
					icon: '',
					content: 'Additional repayments of up to $10K per fixed year'
				},
				{
					icon: '',
					content: 'No interest offset'
				},
				{
					icon: '',
					content: 'No redraw facility'
				}
			],
			featuresOther: [
				{
					icon: '',
					content: 'No annual fee'
				},
				{
					icon: '',
					content: 'No account-keeping fees'
				},
				{
					icon: '',
					content: 'Additional fees may apply'
				}
			],
			alertInfo: {
				collapsed: true,
				content: 'You could save $59,612.37 and pay off your loan 4 years and 4 months quicker',
			},
		}
	];

	// CARD OPTIONS
	$scope.cardOptions = {
		featuresCollapsed: true,
		toggleFeatures: function () {
			$scope.cardOptions.featuresCollapsed = !$scope.cardOptions.featuresCollapsed;
		},
		alignFeatureListHeight: function () {
			if (mediaQuery == media_xs) {
				return;
			}
			else {
				$timeout(function () {
					// LIST CONTAINER HEIGHT CHANGING WAY
					// get lists in all cards
					matchHeight('.match-height-1');
					matchHeight('.match-height-2');
				});
			}
		},
		// MARK: need scenario
		toggleAlert: function ($event, cardInfo) {
			cardInfo.alertCollapsed = !cardInfo.alertCollapsed;
			var element = $event.target;
			if (cardInfo.alertCollapsed) {
				$timeout(function () {
					$(element).parents('.homeloan-card').removeClass('alert-mode');
					$(element).parents('.card-slider').removeClass('alert-mode');
				}, $scope.animationInfo.collapseDuration);
			}
			else {
				$(element).parents('.card-slider').find('.homeloan-card').removeClass('alert-mode');
				$(element).parents('.homeloan-card').addClass('alert-mode');
				$(element).parents('.card-slider').addClass('alert-mode');
			}
		}
	};

	// MARK: RATE CODES
	// v2.0 - manage all the rate codes here
	var _findRates = function (product, purpose, repayment, deposit, frlYear = 1, withOA = false) {
		// product: MS | OS | FRL
		// purpose: OO | INV
		// repayment: P&I | IO 
		// deposit: 60 | 6070 | 7080 | 8090 | 9095
		// frlYear: 1 | 2 | 3 | 4 | 5 (FRL only)
		// withOA: true | false - not implemented yet
		
		var cache_key = product + '_' + purpose + '_' + repayment + '_' + deposit + '_' + frlYear + (withOA ? '_OA' : ''); // FRL_OO_P&I_7080
		// console.log('CACHE KEY: ' + cache_key);

		// search cache
		var cache_vale = _RATES_CACHE[cache_key];
		if( cache_vale ) {
			return cache_vale;
		}

		// cache not found
		var code1 = '';
		var code2 = ''; // comparison

		if( product == 'MS' ) {
			if (purpose == 'OO') {
				if (repayment == 'P&I') {
					if (deposit == '60') {
						code1 = 'MS_PI_OO_MIN150_LVR50_60';
						code2 = 'CP_MS_PI_OO_MIN150_LVR50_60';
					}
					else if (deposit == '6070') {
						code1 = 'MS_PI_OO_MIN150_LVR60_70';
						code2 = 'CP_MS_PI_OO_MIN150_LVR60_70';
					}
					else if (deposit == '7080') {
						code1 = 'MS_PI_OO_MIN150_LVR70_80';
						code2 = 'CP_MS_PI_OO_MIN150_LVR70_80';
					}
					else if (deposit == '8090') {
						code1 = 'MS_PI_OO_MIN150_LVR80_90';
						code2 = 'CP_MS_PI_OO_MIN150_LVR80_90';
					}
					else if (deposit == '9095') {
						code1 = 'MS_PI_OO_MIN150_LVR90_95';
						code2 = 'CP_MS_PI_OO_MIN150_LVR90_95';
					}
				}
				else if (repayment == 'IO') {
					if (deposit == '60') {
						code1 = 'MS_IO_OO_MIN150_LVR50_60';
						code2 = 'CP_MS_IO_OO_MIN150_LVR50_60';
					}
					else if (deposit == '6070') {
						code1 = 'MS_IO_OO_MIN150_LVR60_70';
						code2 = 'CP_MS_IO_OO_MIN150_LVR60_70';
					}
					else if (deposit == '7080') {
						code1 = 'MS_IO_OO_MIN150_LVR70_80';
						code2 = 'CP_MS_IO_OO_MIN150_LVR70_80';
					}
				}
			}
			else if (purpose == 'INV') {
				if (repayment == 'P&I') {
					if (deposit == '60') {
						code1 = 'MS_PI_INV_MIN150_LVR50_60';
						code2 = 'CP_MS_PI_INV_MIN150_LVR50_60';
					}
					else if (deposit == '6070') {
						code1 = 'MS_PI_INV_MIN150_LVR60_70';
						code2 = 'CP_MS_PI_INV_MIN150_LVR60_70';
					}
					else if (deposit == '7080') {
						code1 = 'MS_PI_INV_MIN150_LVR70_80';
						code2 = 'CP_MS_PI_INV_MIN150_LVR70_80';
					}
					else if (deposit == '8090') {
						code1 = 'MS_PI_INV_MIN150_LVR80_90';
						code2 = 'CP_MS_PI_INV_MIN150_LVR80_90';
					}
				}
				else if (repayment == 'IO') {
					if (deposit == '60') {
						code1 = 'MS_IO_INV_MIN150_LVR50_60';
						code2 = 'CP_MS_IO_INV_MIN150_LVR50_60';
					}
					else if (deposit == '6070') {
						code1 = 'MS_IO_INV_MIN150_LVR60_70';
						code2 = 'CP_MS_IO_INV_MIN150_LVR60_70';
					}
					else if (deposit == '7080') {
						code1 = 'MS_IO_INV_MIN150_LVR70_80';
						code2 = 'CP_MS_IO_INV_MIN150_LVR70_80';
					}
					else if (deposit == '8090') {
						code1 = 'MS_IO_INV_MIN150_LVR80_90';
						code2 = 'CP_MS_IO_INV_MIN150_LVR80_90';
					}
				}
			}
		}
		else if( product == 'OA' ) {
			if (purpose == 'OO') {
				if (repayment == 'P&I') {
					if (deposit == '60') {
						code1 = 'OA_PI_OO_MIN150_LVR50_60';
						code2 = 'CP_OA_PI_OO_MIN150_LVR50_60';
					}
					else if (deposit == '6070') {
						code1 = 'OA_PI_OO_MIN150_LVR60_70';
						code2 = 'CP_OA_PI_OO_MIN150_LVR60_70';
					}
					else if (deposit == '7080') {
						code1 = 'OA_PI_OO_MIN150_LVR70_80';
						code2 = 'CP_OA_PI_OO_MIN150_LVR70_80';
					}
					else if (deposit == '8090') {
						code1 = 'OA_PI_OO_MIN150_LVR80_90';
						code2 = 'CP_OA_PI_OO_MIN150_LVR80_90';
					}
					else if (deposit == '9095') {
						code1 = 'OA_PI_OO_MIN150_LVR90_95';
						code2 = 'CP_OA_PI_OO_MIN150_LVR90_95';
					}
				}
				else if (repayment == 'IO') {
					if (deposit == '60') {
						code1 = 'OA_IO_OO_MIN150_LVR50_60';
						code2 = 'CP_OA_IO_OO_MIN150_LVR50_60';
					}
					else if (deposit == '6070') {
						code1 = 'OA_IO_OO_MIN150_LVR60_70';
						code2 = 'CP_OA_IO_OO_MIN150_LVR60_70';
					}
					else if (deposit == '7080') {
						code1 = 'OA_IO_OO_MIN150_LVR70_80';
						code2 = 'CP_OA_IO_OO_MIN150_LVR70_80';
					}
				}
			}
			else if (purpose == 'INV') {
				if (repayment == 'P&I') {
					if (deposit == '60') {
						code1 = 'OA_PI_INV_MIN150_LVR50_60';
						code2 = 'CP_OA_PI_INV_MIN150_LVR50_60';
					}
					else if (deposit == '6070') {
						code1 = 'OA_PI_INV_MIN150_LVR60_70';
						code2 = 'CP_OA_PI_INV_MIN150_LVR60_70';
					}
					else if (deposit == '7080') {
						code1 = 'OA_PI_INV_MIN150_LVR70_80';
						code2 = 'CP_OA_PI_INV_MIN150_LVR70_80';
					}
					else if (deposit == '8090') {
						code1 = 'OA_PI_INV_MIN150_LVR80_90';
						code2 = 'CP_OA_PI_INV_MIN150_LVR80_90';
					}
				}
				else if (repayment == 'IO') {
					if (deposit == '60') {
						code1 = 'OA_IO_INV_MIN150_LVR50_60';
						code2 = 'CP_OA_IO_INV_MIN150_LVR50_60';
					}
					else if (deposit == '6070') {
						code1 = 'OA_IO_INV_MIN150_LVR60_70';
						code2 = 'CP_OA_IO_INV_MIN150_LVR60_70';
					}
					else if (deposit == '7080') {
						code1 = 'OA_IO_INV_MIN150_LVR70_80';
						code2 = 'CP_OA_IO_INV_MIN150_LVR70_80';
					}
					else if (deposit == '8090') {
						code1 = 'OA_IO_INV_MIN150_LVR80_90';
						code2 = 'CP_OA_IO_INV_MIN150_LVR80_90';
					}
				}
			}
		}
		else if( product == 'FRL' ) {
			if (purpose == 'OO') {
				// withOA
				if (withOA) {
					if (repayment == 'P&I') {
						if (deposit == '60' || deposit == '6070') {
							if(frlYear == '1') {
								code1 = 'FRL_OA_1_YEAR_LVR70';
								code2 = 'COMP_FRL_OA_1_YEAR_LVR70';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_OA_2_YEARS_LVR70';
								code2 = 'COMP_FRL_OA_2_YEARS_LVR70';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_OA_3_YEARS_LVR70';
								code2 = 'COMP_FRL_OA_3_YEARS_LVR70';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_OA_4_YEARS_LVR70';
								code2 = 'COMP_FRL_OA_4_YEARS_LVR70';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_OA_5_YEARS_LVR70';
								code2 = 'COMP_FRL_OA_5_YEARS_LVR70';
							}
						}
						else if (deposit == '7080') {
							if(frlYear == '1') {
								code1 = 'FRL_OA_1_YEAR_LVR70_80';
								code2 = 'COMP_FRL_OA_1_YEAR_LVR70_80';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_OA_2_YEARS_LVR70_80';
								code2 = 'COMP_FRL_OA_2_YEARS_LVR70_80';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_OA_3_YEARS_LVR70_80';
								code2 = 'COMP_FRL_OA_3_YEARS_LVR70_80';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_OA_4_YEARS_LVR70_80';
								code2 = 'COMP_FRL_OA_4_YEARS_LVR70_80';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_OA_5_YEARS_LVR70_80';
								code2 = 'COMP_FRL_OA_5_YEARS_LVR70_80';
							}
						}
						else if (deposit == '8090') {
							if(frlYear == '1') {
								code1 = 'FRL_OA_1_YEAR_LVR80_90';
								code2 = 'COMP_FRL_OA_1_YEAR_LVR80_90';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_OA_2_YEARS_LVR80_90';
								code2 = 'COMP_FRL_OA_2_YEARS_LVR80_90';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_OA_3_YEARS_LVR80_90';
								code2 = 'COMP_FRL_OA_3_YEARS_LVR80_90';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_OA_4_YEARS_LVR80_90';
								code2 = 'COMP_FRL_OA_4_YEARS_LVR80_90';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_OA_5_YEARS_LVR80_90';
								code2 = 'COMP_FRL_OA_5_YEARS_LVR80_90';
							}
						}
						else if (deposit == '9095') {
							if(frlYear == '1') {
								code1 = 'FRL_OA_1_YEAR_LVR90_95';
								code2 = 'COMP_FRL_OA_1_YEAR_LVR90_95';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_OA_2_YEARS_LVR90_95';
								code2 = 'COMP_FRL_OA_2_YEARS_LVR90_95';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_OA_3_YEARS_LVR90_95';
								code2 = 'COMP_FRL_OA_3_YEARS_LVR90_95';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_OA_4_YEARS_LVR90_95';
								code2 = 'COMP_FRL_OA_4_YEARS_LVR90_95';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_OA_5_YEARS_LVR90_95';
								code2 = 'COMP_FRL_OA_5_YEARS_LVR90_95';
							}
						}
					}
					else if (repayment == 'IO') {
						if (deposit == '60' || deposit == '6070') {
							if(frlYear == '1') {
								code1 = 'FRL_OA_1_YEAR_IO_LVR70';
								code2 = 'CP_FRL_OA_1_YEAR_IO_LVR70';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_OA_2_YEARS_IO_LVR70';
								code2 = 'CP_FRL_OA_2_YEARS_IO_LVR70';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_OA_3_YEARS_IO_LVR70';
								code2 = 'CP_FRL_OA_3_YEARS_IO_LVR70';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_OA_4_YEARS_IO_LVR70';
								code2 = 'CP_FRL_OA_4_YEARS_IO_LVR70';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_OA_5_YEARS_IO_LVR70';
								code2 = 'CP_FRL_OA_5_YEARS_IO_LVR70';
							}
						}
						else if (deposit == '7080') {
							if(frlYear == '1') {
								code1 = 'FRL_OA_1_YEAR_IO_LVR70_80';
								code2 = 'CP_FRL_OA_1_YEAR_IO_LVR70_80';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_OA_2_YEARS_IO_LVR70_80';
								code2 = 'CP_FRL_OA_2_YEARS_IO_LVR70_80';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_OA_3_YEARS_IO_LVR70_80';
								code2 = 'CP_FRL_OA_3_YEARS_IO_LVR70_80';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_OA_4_YEARS_IO_LVR70_80';
								code2 = 'CP_FRL_OA_4_YEARS_IO_LVR70_80';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_OA_5_YEARS_IO_LVR70_80';
								code2 = 'CP_FRL_OA_5_YEARS_IO_LVR70_80';
							}
						}
					}
				}
				// withour OA
				else {
					if (repayment == 'P&I') {
						if (deposit == '60' || deposit == '6070') {
							if(frlYear == '1') {
								code1 = 'FRL_1_YEAR_LVR70';
								code2 = 'COMP_FRL_1_YEAR_LVR70';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_2_YEARS_LVR70';
								code2 = 'COMP_FRL_2_YEARS_LVR70';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_3_YEARS_LVR70';
								code2 = 'COMP_FRL_3_YEARS_LVR70';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_4_YEARS_LVR70';
								code2 = 'COMP_FRL_4_YEARS_LVR70';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_5_YEARS_LVR70';
								code2 = 'COMP_FRL_5_YEARS_LVR70';
							}
						}
						else if (deposit == '7080') {
							if(frlYear == '1') {
								code1 = 'FRL_1_YEAR_LVR70_80';
								code2 = 'COMP_FRL_1_YEAR_LVR70_80';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_2_YEARS_LVR70_80';
								code2 = 'COMP_FRL_2_YEARS_LVR70_80';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_3_YEARS_LVR70_80';
								code2 = 'COMP_FRL_3_YEARS_LVR70_80';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_4_YEARS_LVR70_80';
								code2 = 'COMP_FRL_4_YEARS_LVR70_80';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_5_YEARS_LVR70_80';
								code2 = 'COMP_FRL_5_YEARS_LVR70_80';
							}
						}
						else if (deposit == '8090') {
							if(frlYear == '1') {
								code1 = 'FRL_1_YEAR_LVR80_90';
								code2 = 'COMP_FRL_1_YEAR_LVR80_90';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_2_YEARS_LVR80_90';
								code2 = 'COMP_FRL_2_YEARS_LVR80_90';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_3_YEARS_LVR80_90';
								code2 = 'COMP_FRL_3_YEARS_LVR80_90';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_4_YEARS_LVR80_90';
								code2 = 'COMP_FRL_4_YEARS_LVR80_90';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_5_YEARS_LVR80_90';
								code2 = 'COMP_FRL_5_YEARS_LVR80_90';
							}
						}
						else if (deposit == '9095') {
							if(frlYear == '1') {
								code1 = 'FRL_1_YEAR_LVR90_95';
								code2 = 'COMP_FRL_1_YEAR_LVR90_95';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_2_YEARS_LVR90_95';
								code2 = 'COMP_FRL_2_YEARS_LVR90_95';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_3_YEARS_LVR90_95';
								code2 = 'COMP_FRL_3_YEARS_LVR90_95';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_4_YEARS_LVR90_95';
								code2 = 'COMP_FRL_4_YEARS_LVR90_95';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_5_YEARS_LVR90_95';
								code2 = 'COMP_FRL_5_YEARS_LVR90_95';
							}
						}
					}
					else if (repayment == 'IO') {
						if (deposit == '60' || deposit == '6070') {
							if(frlYear == '1') {
								code1 = 'FRL_1_YEAR_IO_LVR70';
								code2 = 'CP_FRL_1_YEAR_IO_LVR70';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_2_YEARS_IO_LVR70';
								code2 = 'CP_FRL_2_YEARS_IO_LVR70';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_3_YEARS_IO_LVR70';
								code2 = 'CP_FRL_3_YEARS_IO_LVR70';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_4_YEARS_IO_LVR70';
								code2 = 'CP_FRL_4_YEARS_IO_LVR70';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_5_YEARS_IO_LVR70';
								code2 = 'CP_FRL_5_YEARS_IO_LVR70';
							}
						}
						else if (deposit == '7080') {
							if(frlYear == '1') {
								code1 = 'FRL_1_YEAR_IO_LVR70_80';
								code2 = 'CP_FRL_1_YEAR_IO_LVR70_80';
							}
							else if(frlYear == '2') {
								code1 = 'FRL_2_YEARS_IO_LVR70_80';
								code2 = 'CP_FRL_2_YEARS_IO_LVR70_80';
							}
							else if(frlYear == '3') {
								code1 = 'FRL_3_YEARS_IO_LVR70_80';
								code2 = 'CP_FRL_3_YEARS_IO_LVR70_80';
							}
							else if(frlYear == '4') {
								code1 = 'FRL_4_YEARS_IO_LVR70_80';
								code2 = 'CP_FRL_4_YEARS_IO_LVR70_80';
							}
							else if(frlYear == '5') {
								code1 = 'FRL_5_YEARS_IO_LVR70_80';
								code2 = 'CP_FRL_5_YEARS_IO_LVR70_80';
							}
						}
					}
				}
			}
			else if (purpose == 'INV') {
				if (repayment == 'P&I') {
					if (deposit == '60' || deposit == '6070') {
						if(frlYear == '1') {
							code1 = 'FRL_INV_1_YEAR_LVR70';
							code2 = 'COMP_FRL_INV_1_YEAR_LVR70';
						}
						else if(frlYear == '2') {
							code1 = 'FRL_INV_2_YEARS_LVR70';
							code2 = 'COMP_FRL_INV_2_YEARS_LVR70';
						}
						else if(frlYear == '3') {
							code1 = 'FRL_INV_3_YEARS_LVR70';
							code2 = 'COMP_FRL_INV_3_YEARS_LVR70';
						}
						else if(frlYear == '4') {
							code1 = 'FRL_INV_4_YEARS_LVR70';
							code2 = 'COMP_FRL_INV_4_YEARS_LVR70';
						}
						else if(frlYear == '5') {
							code1 = 'FRL_INV_5_YEARS_LVR70';
							code2 = 'COMP_FRL_INV_5_YEARS_LVR70';
						}
					}
					else if (deposit == '7080') {
						if(frlYear == '1') {
							code1 = 'FRL_INV_1_YEAR_LVR70_80';
							code2 = 'COMP_FRL_INV_1_YEAR_LVR70_80';
						}
						else if(frlYear == '2') {
							code1 = 'FRL_INV_2_YEARS_LVR70_80';
							code2 = 'COMP_FRL_INV_2_YEARS_LVR70_80';
						}
						else if(frlYear == '3') {
							code1 = 'FRL_INV_3_YEARS_LVR70_80';
							code2 = 'COMP_FRL_INV_3_YEARS_LVR70_80';
						}
						else if(frlYear == '4') {
							code1 = 'FRL_INV_4_YEARS_LVR70_80';
							code2 = 'COMP_FRL_INV_4_YEARS_LVR70_80';
						}
						else if(frlYear == '5') {
							code1 = 'FRL_INV_5_YEARS_LVR70_80';
							code2 = 'COMP_FRL_INV_5_YEARS_LVR70_80';
						}
					}
					else if (deposit == '8090') {
						if(frlYear == '1') {
							code1 = 'FRL_INV_1_YEAR_LVR80_90';
							code2 = 'COMP_FRL_INV_1_YEAR_LVR80_90';
						}
						else if(frlYear == '2') {
							code1 = 'FRL_INV_2_YEARS_LVR80_90';
							code2 = 'COMP_FRL_INV_2_YEARS_LVR80_90';
						}
						else if(frlYear == '3') {
							code1 = 'FRL_INV_3_YEARS_LVR80_90';
							code2 = 'COMP_FRL_INV_3_YEARS_LVR80_90';
						}
						else if(frlYear == '4') {
							code1 = 'FRL_INV_4_YEARS_LVR80_90';
							code2 = 'COMP_FRL_INV_4_YEARS_LVR80_90';
						}
						else if(frlYear == '5') {
							code1 = 'FRL_INV_5_YEARS_LVR80_90';
							code2 = 'COMP_FRL_INV_5_YEARS_LVR80_90';
						}
					}
				}
				else if (repayment == 'IO') {
					if (deposit == '60' || deposit == '6070') {
						if(frlYear == '1') {
							code1 = 'FRL_INV_1_YEAR_IO_LVR70';
							code2 = 'CP_FRL_INV_1_YEAR_IO_LVR70';
						}
						else if(frlYear == '2') {
							code1 = 'FRL_INV_2_YEARS_IO_LVR70';
							code2 = 'CP_FRL_INV_2_YEARS_IO_LVR70';
						}
						else if(frlYear == '3') {
							code1 = 'FRL_INV_3_YEARS_IO_LVR70';
							code2 = 'CP_FRL_INV_3_YEARS_IO_LVR70';
						}
						else if(frlYear == '4') {
							code1 = 'FRL_INV_4_YEARS_IO_LVR70';
							code2 = 'CP_FRL_INV_4_YEARS_IO_LVR70';
						}
						else if(frlYear == '5') {
							code1 = 'FRL_INV_5_YEARS_IO_LVR70';
							code2 = 'CP_FRL_INV_5_YEARS_IO_LVR70';
						}
					}
					else if (deposit == '7080') {
						if(frlYear == '1') {
							code1 = 'FRL_INV_1_YEAR_IO_LVR70_80';
							code2 = 'CP_FRL_INV_1_YEAR_IO_LVR70_80';
						}
						else if(frlYear == '2') {
							code1 = 'FRL_INV_2_YEARS_IO_LVR70_80';
							code2 = 'CP_FRL_INV_2_YEARS_IO_LVR70_80';
						}
						else if(frlYear == '3') {
							code1 = 'FRL_INV_3_YEARS_IO_LVR70_80';
							code2 = 'CP_FRL_INV_3_YEARS_IO_LVR70_80';
						}
						else if(frlYear == '4') {
							code1 = 'FRL_INV_4_YEARS_IO_LVR70_80';
							code2 = 'CP_FRL_INV_4_YEARS_IO_LVR70_80';
						}
						else if(frlYear == '5') {
							code1 = 'FRL_INV_5_YEARS_IO_LVR70_80';
							code2 = 'CP_FRL_INV_5_YEARS_IO_LVR70_80';
						}
					}
					else if (deposit == '8090') {
						if(frlYear == '1') {
							code1 = 'FRL_INV_1_YEAR_IO_LVR80_90';
							code2 = 'CP_FRL_INV_1_YEAR_IO_LVR80_90';
						}
						else if(frlYear == '2') {
							code1 = 'FRL_INV_2_YEARS_IO_LVR80_90';
							code2 = 'CP_FRL_INV_2_YEARS_IO_LVR80_90';
						}
						else if(frlYear == '3') {
							code1 = 'FRL_INV_3_YEARS_IO_LVR80_90';
							code2 = 'CP_FRL_INV_3_YEARS_IO_LVR80_90';
						}
						else if(frlYear == '4') {
							code1 = 'FRL_INV_4_YEARS_IO_LVR80_90';
							code2 = 'CP_FRL_INV_4_YEARS_IO_LVR80_90';
						}
						else if(frlYear == '5') {
							code1 = 'FRL_INV_5_YEARS_IO_LVR80_90';
							code2 = 'CP_FRL_INV_5_YEARS_IO_LVR80_90';
						}
					}
				}
			}
		}

		var rate1 = $scope.mainInfo.getInterestRateByCode(code1);
		var rate2 = $scope.mainInfo.getInterestRateByCode(code2); // comparison
		var item = {"rate1": rate1, "rate2": rate2};

		// console.log(`Product: ${product}, Purpose: ${purpose}, Repayment: ${repayment}, Deposit: ${deposit}`);
		// console.log(item);

		// add to cache
		if ( rate1 != null && rate2 != null ) {
			_RATES_CACHE[cache_key] = item;
		}

		return item;
	};
	
	// TOOLTIP, POPOVER, MODAL
	$scope.fixedRateTableInfo = {
		selected: {
			tableIndex: 0,
			selectedRowIndex: 0,
		},
		
		tableInfos: [],

		updateFixedInterestRates: function (tableIndex, rowIndex) {
			var withOA = {
				titleHtml: '',
				rateInfos: [],
			};

			var withoutOA = {
				titleHtml: '',
				rateInfos: [],
			}

			var repayment;
			var repayType = $scope.calcOptions.optionRepayment.selected;
			if (repayType == 0) repayment = 'P&I';
			else if (repayType == 1) repayment = 'IO';

			var lvr;
			var deposit = $scope.calcOptions.optionDeposit.selected.value;
			if (deposit == 0) lvr = '60';
			else if (deposit == 1) lvr = '6070';
			else if (deposit == 2) lvr = '7080';
			else if (deposit == 3) lvr = '8090';
			else if (deposit == 4) lvr = '9095';

			var purp;
			var purpose = $scope.calcOptions.optionPurpose.selected;
			if (purpose == 0) {
				purp = 'OO';
				
				for(var i=0; i<5; i++) {
					var year = i + 1;

					var rates = _findRates('FRL', purp, repayment, lvr, year, true);
					var rateInfo = {
						year: year,
						fixed: rates.rate1,
						comparison: rates.rate2,
						combined: true,
						specialOffer: 3,
					};
					withOA.rateInfos.push(rateInfo);

					var rates = _findRates('FRL', purp, repayment, lvr, year, false);
					var rateInfo = {
						year: year,
						fixed: rates.rate1,
						comparison: rates.rate2,
						combined: false,
						specialOffer: 4,
					};
					withoutOA.rateInfos.push(rateInfo);
				}

				withOA.titleHtml = 'When combined with a variable <span class="color-orange bold">Orange Advantage</span> home loan';
				withoutOA.titleHtml = 'When <strong>NOT</strong> combined with a variable <span class="color-orange bold">Orange Advantage</span> home loan';
				$scope.fixedRateTableInfo.tableInfos = [withOA, withoutOA];

				var lowestRateInfo = getYrRateInfo($scope.fixedRateTableInfo.tableInfos, _compareYear); // v1.4b - getLowestRateInfo
				$scope.fixedRateTableInfo.updateFixedRateCardInfo(lowestRateInfo.tableIndex, lowestRateInfo.rateIndex);
			}
			else if (purpose == 1) {
				purp = 'INV';

				for(var i=0; i<5; i++) {
					var year = i + 1;

					var rates = _findRates('FRL', purp, repayment, lvr, year, false);
					var rateInfo = {
						year: year,
						fixed: rates.rate1,
						comparison: rates.rate2,
					};
					withoutOA.rateInfos.push(rateInfo);
				}

				withoutOA.titleHtml = 'Investor';
				$scope.fixedRateTableInfo.tableInfos = [withoutOA];

				var lowestRateInfo = getYrRateInfo($scope.fixedRateTableInfo.tableInfos, _compareYear); // v1.4b - getLowestRateInfo
				$scope.fixedRateTableInfo.updateFixedRateCardInfo(lowestRateInfo.tableIndex, lowestRateInfo.rateIndex);
			}

			// v1.4b - using getYrRateInfo instead
			function getLowestRateInfo(tableInfos) {
				var tableIndex = 0;
				var rateIndex = 0;
				var lowestInterestRate = Number.MAX_VALUE;

				var tableCount = tableInfos.length;
				for (var i = 0; i < tableCount; i++) {
					var table = tableInfos[i];
					var rateCount = table.rateInfos.length;
					for (var j = 0; j < rateCount; j++) {
						var rate = table.rateInfos[j];
						if (rate.fixed <= lowestInterestRate) {
							lowestInterestRate = rate.fixed
							tableIndex = i;
							rateIndex = j;
						}
					}
				}
				var lowestRateInfo = {
					tableIndex: tableIndex,
					rateIndex: rateIndex
				};
				return lowestRateInfo;
			}

			// v1.4b - always show 3yr
			// v2.0 - add year param
			function getYrRateInfo(tableInfos, year) {
				var tableIndex = 0;
				var lowestInterestRate = Number.MAX_VALUE;
				var yr = year - 1;

				var tableCount = tableInfos.length;
				for (var i = 0; i < tableCount; i++) {
					var table = tableInfos[i];
					var rate = table.rateInfos[yr];
					if (rate.fixed <= lowestInterestRate) {
						lowestInterestRate = rate.fixed
						tableIndex = i;
					}
				}
				var lowestRateInfo = {
					tableIndex: tableIndex,
					rateIndex: 2
				};
				return lowestRateInfo;
			}
		},
		updateFixedRateCardInfo: function (tableIndex, rowIndex) {
			$scope.fixedRateTableInfo.selected.tableIndex = tableIndex;
			$scope.fixedRateTableInfo.selected.rowIndex = rowIndex;

			var rateInfo = $scope.fixedRateTableInfo.tableInfos[tableIndex].rateInfos[rowIndex];

			_update_FRL_CardInterestRatesEx(rateInfo);
			_updateRepayment();
		},
	};

	// ANIMATION
	$scope.animationInfo = {
		addFeatureAnimation: function () {
			$timeout(function () {
				$('.feature-list-transition').addClass('active');
			});
		},
		removeFeatureAnimation: function () {
			$timeout(function () {
				$('.feature-list-transition').removeClass('active');
			});
		},
		collapseDuration: 500,
	};

	// MAIN INFO ADDONS (when the InterestManager is ready, fire this function once in order to update visual area)
	$scope.mainInfo.updateCalculator = function () {
		_updateCalculatorWithPurpose();
	};

	var _updateCalculator = function () {
		_updateCardBaseInfo();
		_updateInterestRate();
		_updateRepayment();
	};
	var _updateCalculatorWithPurpose = function () {
		_updateCardBaseInfo();
		_updateInterestRate();
		_updateFixedRateTableInfoEx();
		_updateRepayment();
	};
	var _updateCardBaseInfo = function () {
		// save frequency for card
		$scope.calcOptions.forCard.frequency = $scope.calcOptions.optionFrequency.selected.name;
		// save description for card
		var option = $scope.calcOptions.optionRepayment.selected == 0 ? 'P&I' : 'interest only';

		// v1.3 show '-' if borrowing amount is too low
		var amount = Number($scope.calcOptions.optionBorrowing.value).formatMoney(0, '.', ',');
		if ($scope.calcOptions.optionBorrowing.showError) {
			amount = '-';
		}

		$scope.calcOptions.forCard.description =
			'Based on a ' +
			$scope.calcOptions.optionLoanTerm.selected.value +
			' year $' +
			amount +
			' loan paying ' +
			option +
			'.';
		$scope.calcOptions.forCard.descriptionFixedRate =
			'For the fixed interest period on a ' +
			$scope.calcOptions.optionLoanTerm.selected.value +
			' year $' +
			amount +
			' loan paying ' +
			($scope.calcOptions.optionRepayment.selected == 0 ? 'P&I' : 'interest only') +
			'.';
	}
	var _updateFixedRateTableInfoEx = function () {
		$scope.fixedRateTableInfo.updateFixedInterestRates();
	};
	var _updateInterestRate = function () {
		_update_MS_CardInterestRates();
		_update_OA_CardInterestRates();
		//_update_FRL_CardInterestRates();

		// 191001 LASH: for FRL update
		_updateFixedRateTableInfoEx();
	};

	var _update_MS_CardInterestRates = function () {
		var cardInfo = $scope.cardInfos[0];
		var interestInfo1 = cardInfo.interestInfo1;
		var interestInfo2 = cardInfo.interestInfo2;

		var purp;
		var purpose = $scope.calcOptions.optionPurpose.selected;
		if (purpose == 0) purp = 'OO';
		else if (purpose == 1) purp = 'INV';
		
		var repayment;
		var repayType = $scope.calcOptions.optionRepayment.selected;
		if (repayType == 0) repayment = 'P&I';
		else if (repayType == 1) repayment = 'IO';

		var lvr;
		var deposit = $scope.calcOptions.optionDeposit.selected.value;
		if (deposit == 0) lvr = '60';
		else if (deposit == 1) lvr = '6070';
		else if (deposit == 2) lvr = '7080';
		else if (deposit == 3) lvr = '8090';
		else if (deposit == 4) lvr = '9095';

		var rates = _findRates('MS', purp, repayment, lvr);
		interestInfo1.rate = rates.rate1;
		interestInfo2.rate = rates.rate2;

		// v1.3 show '-.--' if borrowing amount is too low
		if ($scope.calcOptions.optionBorrowing.showError) {
			interestInfo1.rate = '-.--';
			interestInfo2.rate = '-.--';
		}
	};

	var _update_OA_CardInterestRates = function () {
		var cardInfo = $scope.cardInfos[1];
		var interestInfo1 = cardInfo.interestInfo1;
		var interestInfo2 = cardInfo.interestInfo2;

		var purp;
		var purpose = $scope.calcOptions.optionPurpose.selected;
		if (purpose == 0) purp = 'OO';
		else if (purpose == 1) purp = 'INV';
		
		var repayment;
		var repayType = $scope.calcOptions.optionRepayment.selected;
		if (repayType == 0) repayment = 'P&I';
		else if (repayType == 1) repayment = 'IO';

		var lvr;
		var deposit = $scope.calcOptions.optionDeposit.selected.value;
		if (deposit == 0) lvr = '60';
		else if (deposit == 1) lvr = '6070';
		else if (deposit == 2) lvr = '7080';
		else if (deposit == 3) lvr = '8090';
		else if (deposit == 4) lvr = '9095';

		var rates = _findRates('OA', purp, repayment, lvr);
		interestInfo1.rate = rates.rate1;
		interestInfo2.rate = rates.rate2;

		// v1.3 show '-.--' if borrowing amount is too low
		if ($scope.calcOptions.optionBorrowing.showError) {
			interestInfo1.rate = '-.--';
			interestInfo2.rate = '-.--';
		}
	};
	var _update_FRL_CardInterestRatesEx = function (rateInfo) {
		var cardInfo = $scope.cardInfos[2];
		cardInfo.interestInfo1.rate = rateInfo.fixed;
		// cardInfo.interestInfo1.name = rateInfo.year + ' YR fixed rate <span class="icon-font icon-arrow-down"></span>'; // v1.4b
		cardInfo.interestInfo1.name = _compareYear + 'YR fixed rate'; // v1.4b
		cardInfo.interestInfo2.rate = rateInfo.comparison;
		if (rateInfo.combined == false) {
			cardInfo.specialOffer = 4; // Nothing
		}
		else {
			cardInfo.specialOffer = rateInfo.specialOffer; // 1 OR 2 OR 3
		}

		// v1.3 show '-.--' if borrowing amount is too low
		if ($scope.calcOptions.optionBorrowing.showError) {
			cardInfo.interestInfo1.rate = '-.--';
			cardInfo.interestInfo2.rate = '-.--';
		}
	}

	// v2.0 - not used
	var _getIR = function (code) {
		return $scope.mainInfo.getInterestRateByCode(code);
	};

	var _updateRepayment = function () {
		var repaymentType = $scope.calcOptions.optionRepayment.selected;
		angular.forEach($scope.cardInfos, function (cardInfo) {
			// v1.3 show '-.--' if borrowing amount is too low
			if ($scope.calcOptions.optionBorrowing.showError) {
				cardInfo.repaymentValue = '-';
			}
			else {
				if (repaymentType == 0) {
					cardInfo.repaymentValue = _calculatePrincipalInterest(cardInfo.interestInfo1.rate);
				} else if (repaymentType == 1) {
					cardInfo.repaymentValue = _calculateInterestOnly(cardInfo.interestInfo1.rate);
				}
			}
		});
	};
	var _calculatePrincipalInterest = function (rate) {
		var i = rate * 0.01;
		var R = Number($scope.calcOptions.optionFrequency.selected.value);
		var P = Number($scope.calcOptions.optionBorrowing.value).toFixed(2);
		var N = Number($scope.calcOptions.optionLoanTerm.selected.value);
		// TEST
		// i = 0.05;
		// R = 12;
		// P = 500000;
		// N = 30;
		var x = ((i / R) * P) / (1 - (Math.pow(1 + (i / R), -N * R)));
		return Number(x).formatMoney(0, '.', ',');
	};
	var _calculateInterestOnly = function (rate) {
		var i = rate * 0.01;
		var R = Number($scope.calcOptions.optionFrequency.selected.value);
		var P = Number($scope.calcOptions.optionBorrowing.value).toFixed(2);
		// TEST
		// i = 0.05;
		// R = 12;
		// P = 500000;
		var x = P * (i / R);
		return Number(x).formatMoney(0, '.', ',');
	};

	// v2.0 - the rule has changed
	var _checkDepositIs20Only = function () {
		// var borrowingAmount = Number($scope.calcOptions.optionBorrowing.value);

		// reset
		$scope.calcOptions.optionDeposit.menus[0].hide = false;
		$scope.calcOptions.optionDeposit.menus[1].hide = false;
		$scope.calcOptions.optionDeposit.menus[2].hide = false;
		$scope.calcOptions.optionDeposit.menus[3].hide = false;
		$scope.calcOptions.optionDeposit.menus[4].hide = false;

		// v2.0 - OO & IO, hide 8090 and 9095
		// v2.0 - INV, hide 9095
		// OO & IO - hide 8090 and 9095
		if ( $scope.calcOptions.optionPurpose.selected == 0 && $scope.calcOptions.optionRepayment.selected == 1 ) {
			// select 7080 if 8090 or 9095 was selected before
			if ( $scope.calcOptions.optionDeposit.selected.value == 3 || $scope.calcOptions.optionDeposit.selected.value == 4 ) {
				$scope.calcOptions.optionDeposit.selected = { name: '70.01%-80%', value: 2, hide: false };
			}
			// hide 8090, 9095
			$scope.calcOptions.optionDeposit.menus[3].hide = true;
			$scope.calcOptions.optionDeposit.menus[4].hide = true;
		}
		// INV
		else if ( $scope.calcOptions.optionPurpose.selected == 1 ) {
			// select 8090 if 9095 was selected before
			if ( $scope.calcOptions.optionDeposit.selected.value == 4 ) {
				$scope.calcOptions.optionDeposit.selected = { name: '80.01%-90%', value: 3, hide: false };
			}
			// hide 9095
			$scope.calcOptions.optionDeposit.menus[4].hide = true;
		}
	};


	// WATCH CALCULATOR OPTIONS
	$scope.$watch('calcOptions.optionPurpose.selected', function () {
		_updateCalculatorWithPurpose();

		// v1.3 - disable Deposit options if Invest
		_checkDepositIs20Only();
	});
	$scope.$watch('calcOptions.optionBorrowing.selected', function () {
		if ($scope.calcOptions.optionBorrowing.isFromInput) {
			$scope.calcOptions.optionBorrowing.isFromInput = false;
			return;
		}

		var selected = $scope.calcOptions.optionBorrowing.selected;
		var value = $scope.calcOptions.optionBorrowing.menus[selected].value;
		if ($scope.calcOptions.optionBorrowing.value !== value) {
			$scope.calcOptions.optionBorrowing.isFromRadio = true;
			$scope.calcOptions.optionBorrowing.value = value;
		}
		_updateCalculator();
	});
	$scope.$watch('calcOptions.optionBorrowing.value', function () {
		// avoid recursive loop
		if ($scope.calcOptions.optionBorrowing.isFromRadio) {
			$scope.calcOptions.optionBorrowing.isFromRadio = false;
			return;
		}

		var value = Number($scope.calcOptions.optionBorrowing.value);

		// v1.3 - show error message if value is less than minValue (50000)
		$scope.calcOptions.optionBorrowing.showError = value < $scope.calcOptions.optionBorrowing.minValue ? true : false;

		// v1.3 - disable Deposit options if value is less than depositThreshold (150000)
		_checkDepositIs20Only();

		// for mobile
		var menus = $scope.calcOptions.optionBorrowing.menus;
		for (var index = 0; index < menus.length; index++) {
			if (value < menus[index].threshold) {
				if ($scope.calcOptions.optionBorrowing.selected !== index) {
					$scope.calcOptions.optionBorrowing.isFromInput = true;
					$scope.calcOptions.optionBorrowing.selected = index;
					break;
				}
				break;
			}
		}
		_updateCalculator();
	});
	$scope.$watch('calcOptions.optionDeposit.selected', function () {
		_updateCalculator();
	});
	$scope.$watch('calcOptions.optionRepayment.selected', function () {
		// v1.3 - disable Deposit options if IO
		_checkDepositIs20Only();
		_updateCalculator();
	});
	$scope.$watch('calcOptions.optionFrequency.selected', function () {
		_updateCalculator();
	});
	$scope.$watch('calcOptions.optionLoanTerm.selected', function () {
		_updateCalculator();
	});
	// MARK: this watch only for mobile modal view
	$scope.$watch('calcOptions.optionFrequency.selectedIndex', function () {
		$scope.calcOptions.optionFrequency.selected = $scope.calcOptions.optionFrequency.menus[$scope.calcOptions.optionFrequency.selectedIndex];
	});
	
	// 191001 LASH - this doesn't do anything, commented this part out for now
	//$scope.$watch('calcOptions.optionPurpose.selected', function () {
	//
	//});

	var matchHeight = function( sel ) {
		var listArray = $('.homeloan-card ' + sel);
		var maxHeight = 0;
		var i;
		for (i = 0; i < listArray.length; i++) {
			var list = listArray[i];
			var height = $(list).height();
			if (height > maxHeight) {
				maxHeight = height;
			}
		}
		for (i = 0; i < listArray.length; i++) {
			var list = listArray[i];
			$(list).height(maxHeight);
		}
	};
}]);


// SECOND TAB CONTROLLER
// ----------------------------------------------
angular.module('Homeloan-App').controller('HomeloanToolsController', ["$scope", "$timeout", "$sce", function ($scope, $timeout, $sce) {

	$scope.pageInfo = {
		title: 'In planning mode? Use these calculators to help you:',
	};

	$scope.dom = {
	  borrowingPowerCalculatorBox: $('.content-container.borrowing-power-calculator-box'),
	  calculator: $('#ic-calculator'),
	  calculatorBox: $('.content-container.calculator-box'),
	  calculatorScript: $('#calculator-script')
	};

	$scope.calculatorOptions = {};
	$scope.calculatorOptions.infos = [
		{
			name: 'Repayments calculator',
			script: '<script type="text/javascript" src="https://calculators.infochoice.com.au/Ui/GetScript?clientId=5dedeeb5-c900-42ab-ae01-5e74dda01085&calcId=b9d47181-d8f1-46b4-bed8-e0cec1946c77&target="></script>'
		},
		{
			name: 'Offset calculator',
			script: '<script type="text/javascript" src="https://calculators.infochoice.com.au/Ui/GetScript?clientId=5dedeeb5-c900-42ab-ae01-5e74dda01085&calcId=b598c0b5-3b5d-4276-a1f6-714289a3d346&target="></script>'
		},
		{
			name: 'Extra repayments calculator',
			script: '<script type="text/javascript" src="https://calculators.infochoice.com.au/Ui/GetScript?clientId=5dedeeb5-c900-42ab-ae01-5e74dda01085&calcId=59b5b184-2b6e-43f6-ac20-8c9974705d32&target="></script>'
		},
		{
			name: 'Stamp duty calculator',
			script: '<script type="text/javascript" src="https://calculators.infochoice.com.au/Ui/GetScript?clientId=5dedeeb5-c900-42ab-ae01-5e74dda01085&calcId=edc16223-6f4e-4adb-8174-35f518e62b57&target="></script>'
		},
		{
			name: 'Buying costs calculator',
			script: '<script type="text/javascript" src="https://calculators.infochoice.com.au/Ui/GetScript/?clientId=5dedeeb5-c900-42ab-ae01-5e74dda01085&calcId=c4c62878-b57f-4ec1-87fe-dbbfa41b4872&target="></script>'
		},
		{
			name: 'Lump sum calculator',
			script: '<script type="text/javascript" src="https://calculators.infochoice.com.au/Ui/GetScript?clientId=5dedeeb5-c900-42ab-ae01-5e74dda01085&calcId=b5c83c8c-da8f-40df-be7f-b7438bd5d196&target="></script>'
		},
		{
			name: 'Split loan calculator',
			script: '<script type="text/javascript" src="https://calculators.infochoice.com.au/Ui/GetScript?clientId=5dedeeb5-c900-42ab-ae01-5e74dda01085&calcId=c5823a35-9b9a-44ff-b1fc-0ee05b504fdf&target="></script>'
		},
		{
			name: 'Where can I buy calculator',
			script: '<script type="text/javascript" src="https://calculators.infochoice.com.au/Ui/GetScript?clientId=5dedeeb5-c900-42ab-ae01-5e74dda01085&calcId=71f2649a-1213-421e-9aa9-07bf30e11390&target="></script>'
		},
		{
			name: 'Loan comparison calculator',
			script: '<script type="text/javascript" src="https://calculators.infochoice.com.au/Ui/GetScript/?clientId=5dedeeb5-c900-42ab-ae01-5e74dda01085&calcId=da4caadb-7397-4224-b33c-9fd667393d05&target="></script>'
		},
	];
	$scope.calculatorOptions.selectedIndex = 0;
	$scope.calculatorOptions.selectedInfo = undefined;
	$scope.calculatorOptions.selectCalculator = function (index) {
		$scope.calculatorOptions.selectedIndex = index;

		// if (index === 0) {
		// 	$scope.dom.calculatorBox.hide();
		// 	$scope.dom.borrowingPowerCalculatorBox.show();
		// } else {
			$scope.dom.borrowingPowerCalculatorBox.hide();
			$scope.dom.calculatorBox.show();

			$scope.dom.calculator.html('');
			$scope.dom.calculatorScript.html($scope.calculatorOptions.infos[index].script);
		// }
	};
	$scope.calculatorOptions.changeInfo = function (info) {
		var index = undefined;
		angular.forEach($scope.calculatorOptions.infos, function (object, i) {
			if (object.name === info.name) {
				index = i;
				return;
			}
		});
		if (angular.isDefined(index)) {
			$scope.calculatorOptions.selectCalculator(index);
		}
	};

	$scope.calculatorOptions.moreCalculatorCollapsed = true;
	$scope.calculatorOptions.toggleMoreCalculator = function () {
		$scope.calculatorOptions.moreCalculatorCollapsed = !$scope.calculatorOptions.moreCalculatorCollapsed;
	};
}]);


// THIRD TAB CONTROLLER
// ----------------------------------------------
angular.module('Homeloan-App').controller('HomeloanTipsController', ["$scope", "$timeout", "$sce", function ($scope, $timeout, $sce) {
	$scope.pageInfo = {
		title: 'Tools and resources to help with your home loan:',
	};

	$scope.linkOptions = {};
	$scope.linkOptions.selectedIndex = 0;
	$scope.linkOptions.selectLinkGroupButton = function (index) {
		$scope.linkOptions.selectedIndex = index;
	};
	$scope.linkOptions.infos = [
		{
			name: 'Buy a home',
			links: [
				{
					name: 'First home buyers guide',
					url: 'https://www.ing.com.au/pdf/homeloans/FHB-Guide-DIRECT-1-WEB-SEC.pdf',
					target: '_blank'
				},
				{
					name: 'First home buyers grant',
					url: '/home-loans/tips-hints-guides/first-home-owners-grant.html'
				},
				{
					name: 'Property buyer checklist',
					url: '/pdf/property_buyers_guide.pdf',
					target: '_blank'
				},
				{
					name: 'What\'s the right home loan for me?',
					url: '/home-loans.html'
				},
				{
					name: 'First home buyers FAQ',
					url: '/home-loans/tips-hints-guides/first-home-buyers-faq.html'
				},
				{
					name: 'Finding the home you want',
					url: '/home-loans/tips-hints-guides/finding-the-home-you-want.html'
				},
				{
					name: 'Home loan pre-approval benefits',
					url: '/home-loans/tips-hints-guides/home-loan-pre-approval-benefits.html'
				},
				{
					name: 'How much do I need to borrow?',
					url: '/home-loans/first-home-buyers.html'
				},
				{
					name: 'Compare types of mortgages',
					url: '/home-loans/tips-hints-guides/compare-mortgage-types.html'
				},
				{
					name: 'Deposit and upfront costs for your home loan',
					url: '/home-loans/tips-hints-guides/deposit-and-upfront-costs.html'
				},
				{
					name: 'First Home Buyer Case Study',
					url: '/home-loans/tips-hints-guides/first-home-buyers-case-study.html'
				},
				{
					name: 'Tips for buying at auction',
					url: '/help-and-support/tips-hints-guides/home-loans.html'
				},
				{
					name: 'Interest Only payments',
					url: '/pdf/Interest Only Payments - Fact Sheet.pdf'
				},
			]
		},
		{
			name: 'Invest in<br/> property',
			doubleline: true,
			links: [
				{
					name: 'Reasons for investing in property',
					url: '/home-loans/invest.html'
				},
				{
					name: 'Compare types of mortgages',
					url: '/home-loans/tips-hints-guides/compare-mortgage-types.html'
				},
				{
					name: 'A handy guide to property investment',
					url: '/assets/pdf/handy_guide_to_property_investment.pdf',
					target: '_blank'
				},
				{
					name: '4 easy steps to invest',
					url: '/home-loans/invest.html'
				},
				{
					name: 'More tips for investors',
					url: '/home-loans/invest.html'
				},
				{
					name: 'Investor FAQs',
					url: '/home-loans/invest.html'
				},
				{
					name: 'Investment case study',
					url: '/home-loans/invest.html'
				},
				{
					name: 'Property buyer checklist',
					url: '/pdf/property_buyers_guide.pdf',
					target: '_blank'
				},
				{
					name: 'Deposit and upfront costs for your home loan',
					url: '/home-loans/tips-hints-guides/deposit-and-upfront-costs.html'
				},
				{
					name: 'Tips for buying at auction',
					url: '/help-and-support/tips-hints-guides/home-loans.html'
				},
				{
					name: 'Interest Only payments',
					url: '/pdf/Interest Only Payments - Fact Sheet.pdf'
				},
			]
		},
		{
			name: 'Refinance',
			links: [
				{
					name: 'Reasons to look at home loan refinancing',
					url: '/home-loans/refinance.html'
				},
				{
					name: '4 easy steps to refinance',
					url: '/home-loans/refinance.html'
				},
				{
					name: 'Tips to get the most out of your refinancing efforts',
					url: '/home-loans/refinance.html'
				},
				{
					name: 'What will it cost me to refinance?',
					url: '/home-loans/refinance.html'
				},
				{
					name: 'What to consider before you refinance',
					url: '/home-loans/refinance.html'
				},
			]
		},
	];
	$timeout(function () {
		$('[data-toggle="tab"][data-target="#link-tab-0"]').trigger('click');
	});
}]);


// MOBILE: MODAL CALCULATOR OPTION CONTROLLER
// ----------------------------------------------
angular.module('Homeloan-App').controller('ModalMobileCalculatorController', ["$scope", "$timeout", "$uibModalInstance", "calcOptions", function ($scope, $timeout, $uibModalInstance, calcOptions) {

	$scope.calcOptions = calcOptions;

	$scope.ok = function () {
		$uibModalInstance.close($scope.calcOptions);
	};
	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};

	$scope.clickPopover = function () {
		$('#testPopover').popover({
			content: 'test',
			placement: 'top',
			title: 'test',
			trigger: 'click'
		});
	};
}]);


// MOBILE: MODAL FIXED RATE TABLE CONTROLLER
// ----------------------------------------------
angular.module('Homeloan-App').controller('ModalMobileFixedRateTableController', ["$scope", "$uibModalInstance", "fixedRateTableInfo", "mainInfo", function ($scope, $uibModalInstance, fixedRateTableInfo, mainInfo) {

	$scope.fixedRateTableInfo = fixedRateTableInfo;
	$scope.mainInfo = mainInfo;

	$scope.ok = function () {
		$uibModalInstance.close();
	};
	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};
}]);


// MODAL GENERIC CONTROLLER
// ----------------------------------------------
angular.module('Homeloan-App').controller('ModalGenericController', ["$scope", "$uibModalInstance", function ($scope, $uibModalInstance) {
	$scope.ok = function () {
		$uibModalInstance.close();
	};
	$scope.cancel = function () {
		$uibModalInstance.dismiss('cancel');
	};
}]);


// ANGULAR DYNAMIC NUMBER CONFIG
// ----------------------------------------------
angular.module('Homeloan-App').config(['dynamicNumberStrategyProvider', function (dynamicNumberStrategyProvider) {
	dynamicNumberStrategyProvider.addStrategy('au-dollar', {
		numInt: 12,
		numFract: 2,
		numPos: true,
		numNeg: false,
		numThousand: true,
		numRound: 'round'
	});
}]);


// DROPDOWN SELECTOR (modified by Andy Chin)
// v2.0 - modified to allow update dropdown programmatically
// http://jsfiddle.net/cojahmetov/3DS49/
// ----------------------------------------------
angular.module('Homeloan-App').directive('bsDropdown', ["$compile", function ($compile) {
	return {
		restrict: 'E',
		scope: {
			items: '=dropdownData',
			doSelect: '&selectVal',
			selectedItem: '=preselectedItem'
		},
		link: function (scope, element, attrs) {
			var html = '';
			switch (attrs.menuType) {
				case "button":
					html += '<div class="btn-group btn-block"><button class="btn btn-dropdown-orange btn-block dropdown-toggle symbol-right text-left" data-toggle="dropdown">Action</button><span class="button-symbol"><span class="caret"></span></span>';
					break;
				default:
					html += '<div class="dropdown"><a class="dropdown-toggle" role="button" data-toggle="dropdown"  href="javascript:;">Dropdown<b class="caret"></b></a>';
					break;
			}
			html += '<ul class="dropdown-menu"><li ng-repeat="item in items"><a tabindex="-1" data-ng-click="selectVal(item)" href="javascript:;">{{rawText(item.name)}}</a></li></ul></div>';
			element.append($compile(html)(scope));
			for (var i = 0; i < scope.items.length; i++) {
				if (scope.items[i].name === scope.selectedItem.name) {
					scope.bSelectedItem = scope.items[i];
					break;
				}
			}
			scope.selectVal = function (item) {
				switch (attrs.menuType) {
					case "button":
						$('button.dropdown-toggle', element).html(item.name);
						break;
					default:
						$('a.dropdown-toggle', element).html('<b class="caret"></b> ' + item.name);
						break;
				}
				scope.doSelect({
					selectedVal: item
				});
			};
			scope.rawText = function (text) {
				return $('<div>').html(text).text();
			},
			scope.selectVal(scope.bSelectedItem);
		}
	};
}]);

// v2.0 
// - updated the existing one (above) to allow dynamic update of items in the dropdown
// - doing this on the existing one cause issues on calculator buttons
angular.module('Homeloan-App').directive('bsDropdownNew', ["$compile", function ($compile) {
	return {
		restrict: 'E',
		scope: {
			items: '=dropdownData',
			doSelect: '&selectVal',
			selectedItem: '=preselectedItem'
		},
		link: function (scope, element, attrs) {
			var html = '';
			switch (attrs.menuType) {
				case "button":
					html += '<div class="btn-group btn-block"><button class="btn btn-dropdown-orange btn-block dropdown-toggle symbol-right text-left" data-toggle="dropdown">Action</button><span class="button-symbol"><span class="caret"></span></span>';
					break;
				default:
					html += '<div class="dropdown"><a class="dropdown-toggle" role="button" data-toggle="dropdown"  href="javascript:;">Dropdown<b class="caret"></b></a>';
					break;
			}
			// v2.0
			html += '<ul class="dropdown-menu"><li ng-repeat="item in items" ng-if="!item.hide"><a tabindex="-1" data-ng-click="selectVal(item)" href="javascript:;">{{rawText(item.name)}}</a></li></ul></div>';
			element.append($compile(html)(scope));

			// v2.0
			// for (var i = 0; i < scope.items.length; i++) {
			// 	if (scope.items[i].name === scope.selectedItem.name) {
			// 		scope.selectedItem = scope.items[i];
			// 		break;
			// 	}
			// }

			scope.selectVal = function (item) {
				// Update display based on menuType
				switch (attrs.menuType) {
					case "button":
						$('button.dropdown-toggle', element).html(item.name);
						break;
					default:
						$('a.dropdown-toggle', element).html('<b class="caret"></b> ' + item.name);
						break;
				}
				// Call the callback function
				scope.doSelect({
					selectedVal: item
				});
			};

			scope.rawText = function (text) {
				return $('<div>').html(text).text();
			};

			// v2.0 - Watch for changes to selectedItem
			scope.$watch('selectedItem', function (newValue) {
				if (newValue) {
					scope.selectVal(newValue);
				}
			});
			
			// v2.0 - Initialize the dropdown with preselectedItem (updated)
			if (scope.selectedItem) {
				scope.selectVal(scope.selectedItem);
			}
		}
	};
}]);


// INTEREST RATE DIRECTIVE
// ----------------------------------------------
angular.module('Homeloan-App').directive('lcInterestRate', ["$compile", "$timeout", function ($compile, $timeout) {
	return {
		restrict: 'A',
		scope: {
			interestRate: '=interestRate'
		},
		link: function (scope, element) {
			scope.$watch('interestRate', function (newVal) {
				if (angular.isDefined(newVal) && newVal !== null) {
					var oldView = element[0].querySelector('.active');
					var newView = element[0].querySelector('.under');
					
					// v1.3
					if (newVal === '-.--') {
						$(newView).text(newVal).addClass('active');
					}
					else {
						$(newView).text(Number(newVal).toFixed(2)).addClass('active');
					}
					$timeout(function () {
						$(newView).removeClass('under');
					});
					$(oldView).addClass('over');
					$timeout(function () {
						$(oldView).removeClass('active').removeClass('over').addClass('under').text('');
					}, 500);
				}
			});
		},
		template: '<div class="rate-box"><span class="active"></span><span class="under"></span></div>'
	};
}]);


// ANGULAR BIND HTML COMPILE
// ----------------------------------------------
angular.module('Homeloan-App').directive('bindHtmlCompile', ['$compile', function ($compile) {
	return {
		restrict: 'A',
		link: function (scope, element, attrs) {
			scope.$watch(function () {
				return scope.$eval(attrs.bindHtmlCompile);
			}, function (value) {
				// Incase value is a TrustedValueHolderType, sometimes it
				// needs to be explicitly called into a string in order to
				// get the HTML string.
				element.html(value && value.toString());
				// If scope is provided use it, otherwise use parent scope
				var compileScope = scope;
				if (attrs.bindHtmlScope) {
					compileScope = scope.$eval(attrs.bindHtmlScope);
				}
				$compile(element.contents())(compileScope);
			});
		}
	};
}]);


// FORMAT MONEY FUNCTION
// ----------------------------------------------
Number.prototype.formatMoney = function (c, d, t) {
	var n = this,
		c = isNaN(c = Math.abs(c)) ? 2 : c,
		d = d == undefined ? "." : d,
		t = t == undefined ? "," : t,
		s = n < 0 ? "-" : "",
		i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
		j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
