/**
 * If the Cupid object hasn't been defined then make it so
 */
if( typeof Cupid == 'undefined' ) {
	var Cupid = {};
}

/**
 * Extends the Cupid object with loan functions (via a deep copy)
 *
 * @see Cupid
 */
$.extend( true, Cupid, {
	Project:
	{
		/**
		 * Contains functions that should relate to loans
		 */
		Loan:
		{
			/**
			 * Restricts a loan term field based on the amount requested
			 *
			 * @param {Object} params An object containing 'form' 'loanAmt' 'selectOption' and 'triggerAmt'
			 * @return void
			 */
			restrictLoanTerm: function( params )
			{
				var form = $( params.form );

				/**
				 * intercept change/keyup/blur events for the loan amount
				 */
				$(form).find( params.loanAmt ).bind( 'change keyup blur', function() {
					/**
					 * Rather than detecting what the keycode is, check to see what the
					 * entered text is and only allow numbers and periods.
					 */
					this.value = this.value.replace( /[^0-9\.]/g, '' );

					/**
					 * Although we can use 'form' here, if we split this up that will cause
					 * errors so just assume we need to find it again.
					 */
					var parentForm = $(this).parents( 'form:last' );

					/**
					 * Get the 18 month option for the current form
					 */
					var selectOption = $(parentForm).find( params.selectOption );

					/**
					 * If they're requesting more than $2000 don't allow the 18 month
					 * repayments
					 */
					if( this.value >= params.triggerAmt )
					{
						$( selectOption ).attr( 'disabled', 'disabled' );
						/**
						 * If the 18 month option is currently selected, we need to change that
						 */
						if( $( selectOption ).attr( 'selected' ) == true )
						{
							/**
							 * So get the next option siblining and set it to selected
							 */
							$( selectOption ).siblings('option:eq(0)').attr( 'selected', 'selected' )
						}
					}
					else
					{
						/**
						 * Once we get under $2000 again we can re-enable the 18 month option
						 */
						$( selectOption ).attr( 'disabled', '' );
					}
				});
			},

			/**
			 * Works out how much repayments would be for a given loan amount
			 *
			 * Taken straight from the old Hidden Brains code, this is some
			 * nasty nasty code and needs a complete re-write.
			 *
			 * @return This always returns false
			 */
			calculateRepayments: function()
			{
				var divid_arr = new Array();
				divid_arr=['errmsg_loanamo'];

				document.getElementById("vLoanAmo").className = 'input';

				/* Reset error messages */
				reset_errmessages(divid_arr);

				var flagerror = 0;

				if(document.getElementById("vLoanAmo").value == "")
				{
					inputvalidation_red('vLoanAmo');
					validation_height('errmsg_loanamo','yes');
					validation_message("errmsg_loanamo","Please Enter Loan Amount","","95","73");
					document.getElementById("vLoanAmo").value = '';
					flagerror ++;
				}
				else if(!isValidAmount(document.getElementById("vLoanAmo").value))
				{
					inputvalidation_red('vLoanAmo');
					validation_height('errmsg_loanamo','yes');
					validation_message("errmsg_loanamo","Please enter valid Loan Amount","","95","48");
					flagerror ++;
				}
				else if(parseInt(document.getElementById("vLoanAmo").value) < "1000" || parseInt(document.getElementById("vLoanAmo").value) > "5000")
				{
					inputvalidation_red('vLoanAmo');
					validation_height('errmsg_loanamo','yes');
					validation_message("errmsg_loanamo","Please enter an amount between $1000 and $5000","","95","1");
					flagerror ++;
				}

				if(flagerror == 0)
				{
					document.getElementById("results_title").style.display = "";
					document.getElementById("repayment_results").style.display = "";
					document.getElementById("repayment_term").style.display = "";
					//document.getElementById("catchup").style.display = "none";
					loan = eval (document.getElementById("vLoanAmo").value);
					rte = eval (document.getElementById("vInterest").value);
					year = eval (document.getElementById("vPeriod").value);
					fee = eval (document.getElementById("vApplicationFee").value);
					amt = loan + fee;
					if (amt == '')
					{
						alert('Principal must be entered.');
						return false;
					}
					if (amt != parseInt(amt) || amt < 1)
					{
						alert('Principal invalid (must be greater than zero).');
						return false;
					}
					var r = eval(rte) / 100;
					if (r == '')
					{
						alert('Interest Rate must be entered.');
						return false;
					}
					if (r != parseFloat(r) || r < 0 || r > 1)
					{
						alert('Interest rate invalid (must be between 0 and 100).');
						return false;
					}
					if (year == '')
					{
						alert('Loan period must be entered.');
						return false;
					}
					if (year != parseFloat(year) || year < 0.25 || year > 50)
					{
						alert('Loan period invalid (must be between 1/4 and 50 years).');
						return false;
					}

			//		For monthly payment
					months = year*12;

					var i = r/12;
					var a = Math.ceil(amt * (i/(1-Math.pow((1+i),-months)))*100);

					var d = Math.floor(a/100);
					var c = a%100;if (c < 10) c = '0'+c;
					k = d+'.'+c;

					document.getElementById('monthly_payment').value=k;
					document.getElementById('Month_Payment_id').style.display='';

			//		For fortnightly payment
					fortnight = year*25.94;

					var ii = r/25.94;
					var aa = Math.ceil(amt * (ii/(1-Math.pow((1+ii),-fortnight)))*100);

					var dd = Math.floor(aa/100);
					var cc = aa%100;if (cc < 10) cc = '0'+cc;
					kk = dd+'.'+cc;

					document.getElementById('fortly_payment').value=kk;
					document.getElementById('Fort_Payment_id').style.display='';

			//		For weekly payment
					week = year*51.83;

					var iii = r/51.83;
					var aaa = Math.ceil(amt * (iii/(1-Math.pow((1+iii),-week)))*100);

					var ddd = Math.floor(aaa/100);
					var ccc = aaa%100;if (ccc < 10) ccc = '0'+ccc;
					kkk = ddd+'.'+ccc;

					document.getElementById('weekly_payment').value=kkk;
					document.getElementById('Week_Payment_id').style.display='';

					return false;
				}
				else
					return false;
			}
		}
	}
});
