function in_array( what, where ){
	var a=false;
	for(var i=0;i<where.length;i++){
	  if(what == where[i]){
	    a=true;
        break;
	  }
	}
	return a;
}



function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '' + num + '.' + cents);
}

function changeValue(fieldId)
{	var newVal = formatCurrency($("#"+fieldId).val());
	//alert(newVal);
	$("#"+fieldId).val(newVal);
}

function showConditional(conditionalClass,conditionalId, value, thisVal)
{	valueArr = value.split(",");
	
	
	
	if(in_array(thisVal, valueArr))
	{	$("."+conditionalClass).css("display", "block");
		$("."+conditionalClass+" input").attr("disabled", "");
		
		if(conditionalId != '' && conditionalId != 'undefined')
		{	$("#"+conditionalId).css("display", "block");
			
		}
		
	} else
	{	$("."+conditionalClass).css("display", "none");
		$("."+conditionalClass+" input").attr("disabled", "disabled");
		if(conditionalId != '' && conditionalId != 'undefined')
		{	$("#"+conditionalId).css("display", "none");
		}
		
		
	}
}

function changeHowlongField(thisId)
{	
	
	var year_val = $("#"+thisId+"_Years").val();
	var month_val = $("#"+thisId+"_Months").val();
	var valid = false;
	
	if(year_val == '' && month_val == '') {
		$("#"+thisId).val('');
		return false;
	}
	
	
	if(year_val == '') {
		year_val = 0;
	}
	
	if(month_val == '') {
		month_val = 0;
	}
	
	
	
	
	var total_months = parseInt(year_val * 12) + parseInt(month_val);
	
	$("#"+thisId).val(total_months);
	
}


function showConditionalAddress(conditionalClass,conditionalId, value, thisId)
{	valueArr = value.split(",");
	//alert(in_array(thisVal, valueArr) + " | " + thisVal + " | " + valueArr);
	
	var year_val = $("#"+thisId+"_Years").val();
	var month_val = $("#"+thisId+"_Months").val();
	var valid = false;
	
	if(year_val == '' && month_val == '') {
		$("#"+thisId).val('');
		return false;
	}
	
	
	if(year_val == '') {
		year_val = 0;
	}
	
	if(month_val == '') {
		month_val = 0;
	}
	
	
	
	
	var total_months = parseInt(year_val * 12) + parseInt(month_val);
	
	$("#"+thisId).val(total_months);
	
	if(total_months < 36) {
		valid = false;
	} else {
		valid = true;
	}
	
	
	
	if(valid == false)
	{	$("."+conditionalClass).css("display", "block");
	
		if(conditionalId != '' && conditionalId != 'undefined')
		{	$("#"+conditionalId).css("display", "block");
			
		}
		
	} else
	{	
	
		if(conditionalClass == 'Property_Tenancy_2') {
			
			$("."+conditionalClass).css("display", "none");
			
			if(conditionalId != '' && conditionalId != 'undefined')
			{	$("#"+conditionalId).css("display", "none");
			}
			
			$(".Property_Tenancy_3").css("display", "none");
			$("#Property_Tenancy_3_row").css("display", "none");
			$(".Property_Tenancy_4").css("display", "none");
			$("#Property_Tenancy_4_row").css("display", "none");
		} else if(conditionalClass == 'Property_Tenancy_3') {
			
			$("."+conditionalClass).css("display", "none");
			
			if(conditionalId != '' && conditionalId != 'undefined')
			{	$("#"+conditionalId).css("display", "none");
			}
			
			
			$(".Property_Tenancy_4").css("display", "none");
			$("#Property_Tenancy_4_row").css("display", "none");
		} else {
			$("."+conditionalClass).css("display", "none");
			
			if(conditionalId != '' && conditionalId != 'undefined')
			{	$("#"+conditionalId).css("display", "none");
			}
		}
		
	}
}


$(document).ready(function() {
	$("#howMuch").keyup(
		function(){
			//daysCalculation($("#howMuch").val(),$("#howMuch").val()*1.25,$("#howLong").val());
		}
	);
	
	$('#howMuch_slider').bind('slidechange', function(event, ui) {
	 //daysCalculation($("#howMuch").val(),$("#howMuch").val()*1.25,$("#howLong").val());
	});
	
	$('#howLong_slider').bind('slidechange', function(event, ui) {
	 //daysCalculation($("#howMuch").val(),$("#howMuch").val()*1.25,$("#howLong").val());
	});
	
	
	
});

function daysCalculation(a,p,n) {
  var x=(p)/a;
  i = Math.pow(x,(365/n))-1;
  Dapr=Math.floor(i*1000+.5)/10;if (Dapr - Math.floor(Dapr) == 0) Dapr = Dapr + ".0";Dapr = Dapr+"%";
  alert("Loan Amount = "+a+"\nMonthly Payment = "+p+"\nPeriod = "+n+"\nAPR = "+Dapr);
return Dapr;
}


function aprCalculation(){
	var p=parseFloat(document.monthly.securedLoanAmount.value);
	var n=parseFloat(document.monthly.numMonths.value);
	var a=parseFloat(document.monthly.monthlyPayment.value);
	k=1;j = .008;ip=j +.001/12;pv = p;
	while (Math.abs(k*12)>.000001){v_ = 1/(1+j);vn=Math.pow(v_,n);pvprev=pv;pv=a*(1-vn)/j;k=(p-pv)/(pvprev-pv)*(ip-j);ip=j;j=j+k;}	
	r12=(Math.pow(1+j,12)-1)*100;apr=Math.floor(r12*10+.5)/10;if (apr - Math.floor(apr) == 0) apr = apr + ".0";apr = apr+"%";
	
	alert("Loan Amount = "+p+"\nMonthly Payment = "+a+"\nPeriod = "+n+"\nAPR = "+apr);
	
	
	return apr;
}


function isValidPostcode(pcode,cssid)
{	var isvalid = true

	
	if(cssid == 'pcode_2' && pcode.toUpperCase() == $("#pcode").val().toUpperCase()) {
		isvalid = false;
		//$("#pcode_2").val('');
		$("#streetname_2").val('');
		$("#streetname2_2").val('');
		$("#town_2").val('');
		$("#county_2").val('');
		alert('This address value cannot be the same as your previous address!');
	}
	
	if(cssid == 'pcode_3' && (pcode.toUpperCase() == $("#pcode_2").val().toUpperCase() || pcode.toUpperCase() == $("#pcode").val().toUpperCase())) {
		isvalid = false;
		//$("#pcode_2").val('');
		$("#streetname_3").val('');
		$("#streetname2_3").val('');
		$("#town_3").val('');
		$("#county_3").val('');
		alert('This address value cannot be the same as your previous address!');
	}

	if(isvalid == true) {
		$.ajax({
		   type: "POST",
		   url: "./ajax/postcode.php",
		   data: { postcode: pcode, token: "18517-bef4b-d4587-000cb", id:2},
		   success: function(msg){
			
			if(msg != 'Invalid postcode' && msg.indexOf("|") > -1)
			{	$("#"+cssid+"_confirm").val(pcode);
				
			
				if(cssid == 'pcode')
				{	var newresult = msg.split("|");
					$("#streetname").val(newresult[0]);
					$("#town").val(newresult[1]);
					$("#county").val(newresult[2]);
				}
				
				if(cssid == 'pcode_2')
				{	var newresult = msg.split("|");
					$("#streetname_2").val(newresult[0]);
					$("#town_2").val(newresult[1]);
					$("#county_2").val(newresult[2]);
				}
				
				if(cssid == 'pcode_3')
				{	var newresult = msg.split("|");
					$("#streetname_3").val(newresult[0]);
					$("#town_3").val(newresult[1]);
					$("#county_3").val(newresult[2]);
				}
				
			} else {
				$("#"+cssid+"_confirm").val(msg);
				
				if(cssid == 'pcode')
				{	$("#streetname").val('');
					$("#town").val('');
					$("#county").val('');
				}
				if(cssid == 'pcode_2')
				{	$("#streetname_2").val('');
					$("#town_2").val('');
					$("#county_2").val('');
				}
				if(cssid == 'pcode_3')
				{	$("#streetname_3").val('');
					$("#town_3").val('');
					$("#county_3").val('');
				}
			}
			
			$('#' + cssid).blur(function() {
				var new_confirm = new LiveValidation(cssid+'_confirm');
				new_confirm.add( Validate.Confirmation, { match: cssid, failureMessage: "Postcode Invalid" } );
				new_confirm.validate();
			});
			
			
		   }
		 });
	}
}



function isValidTelephone(tel,cssid)
{	$.ajax({
		   type: "POST",
		   url: "./ajax/telephone.php",
		   data: { tel: tel},
		   success: function(msg){
			
			if(msg != 'INVALID')
			{	$("#"+cssid+"_confirm").val(tel);
			} else {
				$("#"+cssid+"_confirm").val(msg);
			}
			
			$('#' + cssid).keyup(function() {
				//var new_confirm = new LiveValidation(cssid+'_confirm');
				//new_confirm.add( Validate.Confirmation, { match: cssid, failureMessage: "Telephone Invalid" } );
				//new_confirm.add( Validate.Format, { pattern: /^07/i, failureMessage: "Not a mobile number" } );
				//new_confirm.add( Validate.Length, { minimum: 11 } );
				//new_confirm.validate();
			});
			
			
		   }
		 });
}


function updateDob(fieldId)
{	
	var element_day = document.getElementById(fieldId+"_Day");
	var element_month = document.getElementById(fieldId+"_Month");
	var element_year = document.getElementById(fieldId+"_Year");
	var element_dob = document.getElementById(fieldId);
		
	if(element_day.value != '' && element_month.value != '' && element_year.value != '')
	{	element_dob.value = element_day.value + "/" + element_month.value + "/" + element_year.value;
	} else
	{	element_dob.value = '';
	}
	
}


function updateValid(fieldId, curmonth, curyear)
{	
	var element_month = document.getElementById(fieldId+"_Month");
	var element_year = document.getElementById(fieldId+"_Year");
	var element_date = document.getElementById(fieldId);
	var isvalid = true;
	
	
	if(fieldId == 'validFrom') {
		// execute check that it is in the past
		
		if(element_year.value >= curyear) {
				if(element_year.value == curyear) {

					if(trimNumber(element_month.value) > curmonth) {
						alert('This card has has not started yet');
						isvalid = false;
					} else {
						isvalid = true;
						
					}
				} else {
					alert('This card has has not started yet');
					isvalid = false;
				}
		} else {
			isvalid = true;
		}
		
	}
	
	
	if(fieldId == 'validTo') {
		// execute check that it is in the future
		
		if(element_year.value == curyear) {
				
				if(element_year.value == curyear) {

					if(trimNumber(element_month.value) < curmonth) {
						alert('This card has expired');
						isvalid = false;
					} else {
						isvalid = true;
						
					}
				} else {
					isvalid = false;
				}
				
		} else {
			isvalid = true;
		}
		
	}
	
	
	
	if(isvalid == true) {
		if(element_month.value != '' && element_year.value != '')
		{	element_date.value = element_month.value + "/" + element_year.value;
		} else
		{	element_date.value = '';
		}
	} else {
		element_date.value = '';
	}
	
	var dateCheck = new LiveValidation(fieldId, { validMessage: "" } );
	dateCheck.add( Validate.Presence, { failureMessage: "This date is invalid" } );
	dateCheck.validate();
}


function checkTenancy(fieldId)
{	
	var element_month = document.getElementById(fieldId+"_Month");
	var element_year = document.getElementById(fieldId+"_Year");
	var element_date = document.getElementById(fieldId);
	
	if(element_month.value != '' && element_year.value != '')
	{	element_date.value = element_month.value + "/" + element_year.value;
	} else
	{	element_date.value = '';
	}
	
}

function trimNumber(s) {
  while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
  return s;
}

function sendLv() {
	var howMuch = parseInt($('#howMuch').val());
	var propertyValue = parseInt($('#propertyValue').val());
	var oustandingMortgage = parseInt($('#outstandingMortgage').val());
	
	if ($('#app').val() == 'mortgage') {
		var oustandingMortgage = 0;
	}
	
	if (howMuch != '' && propertyValue != '') {
		
		
		var loanAmount = howMuch + oustandingMortgage;
		var lv = loanAmount/propertyValue;
		
		
		//alert(howMuch + '|' + propertyValue + '|' + oustandingMortgage + '|' +lv);
		
		if (lv > 0.85) {
			
			var suggestedAmount = (propertyValue * 0.85) - oustandingMortgage
			
			if (suggestedAmount < 3000) {
				alert('Unfortunately you do not have enough equity available in your property to secure a loan against its value at the moment.');
			} else {
				if ($('#app').val() == 'mortgage') {
				alert('The loan amount you have applied for is greater than the maximum a lender will grant you in the current market.  Based on the property value, the maximum you can borrow is £' + suggestedAmount + '.  Please adjust the requested amount and try again.');
				} else {
					alert('The loan amount you have applied for is greater than the maximum a lender will grant you in the current market.  Taking into account the value of your house and outstanding mortgage the maximum amount you could borrow is £' + suggestedAmount + '.  Please adjust the requested amount and try again.');
				}
			}
			
			
		} else {
			if (!isNaN(lv)) {
				sendQuickReg();
			}
		}
		
	}
	
}

function sendQuickReg() {
	
	var Title = $('#Title').val();
	var First_Name = $('#First_Name').val();
	var Last_Name = $('#Last_Name').val();
	var Date_Of_Birth = $('#Date_Of_Birth').val();
	var Email_Address = $('#Email_Address').val();
	var Mobile_Number = $('#Mobile_Number').val();
	
	
	$.ajax({
		   type: "POST",
		   url: "./ajax/user_registration.php",
		   data: { Title: Title, First_Name: First_Name, Last_Name: Last_Name, Date_Of_Birth: Date_Of_Birth, Email_Address: Email_Address, Mobile_Number: Mobile_Number},
		   success: function(msg){
			
				$("#next").click();
			
		   }
		 });
}
