/**
FILENAME: application.js
AUTHOR: Ashley Barrett (ashley.barrett@rgroup.co.uk)
CREATED: 03/03/2010
COMMENTS: The javascript file for the new applicatiom form
CHANGE LOG:
	Atti: Added divShowHide for payment guard form
	Ashley Barrett (05/07/2010) Added in ajax functionality to get existing debts for customer updates.
	Ashley Barrett (06/07/2010) Fix to stop every page trying to get the existing debts.
	Chris Cheshire (26/07/2010) Updates to stage two elements for new direct debit page and implementation of print page link
	Chris Cheshire (24/08/2010) Bind enter button to find address button or link only in postcode box
	Crandy (31/08/2010) Removed the default value for salary
	Chris Cheshire 	- 11/02/11 	- Change to attribute of ajax email hidden fields on stage two form submit
	Chris Cheshire 	- 11/04/11 	- Addition of ajax email address validation
*/

$(function()
{
	$("div#YesPaymentAmount").hide();
	
	$("input#SalaryAmount").blur(function(){
		if(($("input#SalaryAmount").val() != '') && ($("select#AmountRequired").val() != -1)){
			getFeeAmount($("input#SalaryAmount").val(), $("select#AmountRequired").val());
		}
	});
	
	
	if(($("input#SalaryAmount").val() != '') && ($("select#AmountRequired").val() != -1)){
		$("input#SalaryAmount").blur();
	}
	
	$("select#AmountRequired").change(function(){
		$("input#SalaryAmount").blur();
	});
	
	$('input#newFormPaymentNext').show();
	
	$('input#EmailAddress').blur(function(){
		if($(this).val() != ''){
			$("img#emailLoader").show();
			$('img#emailTick').hide();
			$('img#emailCross').hide();
			setTimeout (function (){validateEmail();}, 1000);
		}else{
			$("img#emailLoader").hide();
			$("img#emailTick").hide();
			$("img#emailCross").hide();
			$('p.emailAjaxErr').hide();
		}
	});
	
	if($('input#EmailAddress').val() != ''){
		$('input#EmailAddress').blur();
	}
	
	$("a#widgClose").click(function(){
		$('div#modalPage').fadeOut(300);
		return false;
	});
	
	if($("input#hideWidgButton").val() == 1){
		$("div#widgPaymentRest").show();
		$("div#widgButtonHolder").hide();
	}else{
		$("div#widgPaymentRest").hide();
		$("div#widgButtonHolder").show();
	}
	
	$("a#widgResetPayment").click(function(){
		$("div#widgButtonHolder").slideUp("slow");
		$("div#widgPaymentRest").slideDown("slow");
		setWidgetSession();
		
		return false;
	});
	
	if (typeof bypassAddressFinder === "undefined")
	{
		bypassAddressFinder = false;
	}
	
        /**
         *Immediate email followup - turned off 14/11/11
        /*
	if (($("input#autoEmailID").length) && ($("input#EmailAddress").length) && ($("input#autoEmailID").val() != 'DontSend')){
		$(window).unload(function(){
			stage = $("input#autoEmailID").val();
			send = 1;
			
			if(stage == 'st1'){
				affiliateID =  $("input#affiliate").val();
				CID = 1;
				AID = 1;
				Last3 = 1;
			}
			else if(stage == 'st2'){
				affiliateID =  1;
				CID = $("input#immediateEmailCID").val();
				AID = $("input#immediateEmailAID").val();
				Last3 = $("input#immediateEmailLast3").val();
			}
			
			email = $("input#EmailAddress").val();
			firstName = $("input#FirstName").val();
			lastName = $("input#LastName").val();
			
			sendImmediateNoP2PMail(stage, email, firstName, lastName, affiliateID, CID, AID, Last3);
		});
	}
        */

	if($("input#cbsSplitTestNoButton").length > 0){
		$('div#modalPage').show();
		setTimeout (function(){ $('div#modalPage').fadeOut("slow"); },6000);  
	}

	if($(".applicationForm").length > 0){
		$(".applicationForm [title]").tooltip();
	}
	
	//hide the lender page footer links for the app form
	if($(".applicationForm").length > 0){
		$("#lenderPageFooterWrapper").hide();
	}
	
	$('a.printPage').prepend('<a href="#print">Click here to print a copy of this page</a>');
	
	$("a#LFPaperMandate").click(function(){
		window.open("https://secure.loanfinder.co.uk/application/includes/ddPaperDDI", "_blank", "width=1100, height=900, scrollbars=1, top=25, left=110");
		return false;
	});
	
	$('a.printPage a').click(function(){
		window.print();
		return false;
	});
	
	$('a.printDDLF').click(function(){
		window.open("https://secure.loanfinder.co.uk/application/includes/ddPopup?mandate=loanfinder", "_blank", "width=950, height=630");
		return false;
		});
		
	$('a.printDDCX').click(function(){	
		window.open("https://secure.loanfinder.co.uk/application/includes/ddPopup?mandate=creditxtra", "_blank", "width=950, height=630");
		return false;
		});

	
	if ($("input#type").val() !== undefined){
	
		if ($("input#type").attr("class") == "mandate"){
			if ($("input#type").val() === "loanfinder"){
				var payBoxBank = window.opener.document.getElementById('ddLFCheck').innerHTML;
			}else if ($("input#type").val() === "creditxtra"){
				var payBoxBank = window.opener.document.getElementById('ddCXCheck').innerHTML;
			}
			$("div#popupBox").html('<div class="formSection cxddCheck">'+payBoxBank+'</div>');
		}

			$("#printDD").hide();
			$("div#headerContainer").hide();
			$("div#footerContainer").hide();
			$("div#lenderPageFooterWrapper").hide();
			
			window.print();
	}

	
	var creditors = "";
	
	$(".remove").click(function(){
		var remove = $(this).attr("name");
		$(this).removeDebt(remove);
		return false;
	});
	
	// Set up any previously defined bank accounts, so the user can manage them.
	$('.bankAccountsColumn2 A').click(function() {
		$(this).removeBankAccount($(this).parent().prev().html(), parseInt($(this).attr('name')));
		
		return false;
	});
	
	$("#SalaryFrequency").change(function(){
		var option = $("#SalaryFrequency option:selected").text();
		$("#incomePeriod").html(option.toLowerCase() + " ");
	});
	
	//temp code to show auto
	//$("#questionnairePopup").jqm();
	//$("#questionnairePopup").jqmShow();
	
	$("#yourpageLink").click(function(){
		
		//return true;	
		
		if ($.browser.msie && $.browser.version.substr(0,1) < 7) {
			
			return true;
			
		}else{

			$("#questionnairePopup").jqm();
			$("#questionnairePopup").jqmShow();
			
			$("html").scrollTop(0);
			
			$(".questionnairePopupClose").click(function(){
				$("#questionnairePopup").jqmHide(); 
				window.location = '/recommendations/';
				return false;
			});
			
			return false;
			
		}
		
	});
	
	$("#questionnaireProceed").submit(function(){
		
		return true;	
		
		/*
		if ($.browser.msie && $.browser.version.substr(0,1) < 7) {
			
			return true;
			
		}else{
					
			$("#questionnairePopup").jqm();
			$("#questionnairePopup").jqmShow();
			
			$("html").scrollTop(0);
			
			$(".questionnairePopupClose").click(function(){
				$("#questionnairePopup").jqmHide(); 
				window.location = '/recommendations/';
				return false;
			});
			
			return false;
			
		}
		*/
		
	});
	
	$("#questionnaireForm").submit(function(){
		
		var error = false;
		$(".QErrorMessage").hide();
		
		if ($("#answersShown").val() == "1"){
		
			return true;
		
		}else{
		
			if ($("input[name=QPayment]:checked").val() == undefined)
			{
				var error = true;
				$("#QPaymentError").show();
			}
			
			if ($("input[name=QCreditXtra]:checked").val() == undefined)
			{
				var error = true;
				$("#QCreditXtraError").show();
			}
			
			if (error == true){
				
				return false;
				
			}else{
				
				var incorrectAnswers = 0;
				
				$("#answersShown").val("1");
				
				$("#answersSubmitQuestionnaire").val("Proceed to 'My Lenders'");
				
				$(".questionnaireAnswers").hide();				
				
				if ($("input[name=QPayment]:checked").val() == "0"){
					$("p.questionnaireQuestionQPayment").addClass("questionCross");
					$("#QPaymentHelp").show();
					incorrectAnswers++;
				}else{
					$("p.questionnaireQuestionQPayment").addClass("questionTick");	
				}
				
				if ($("input[name=QCreditXtra]:checked").val() == "0"){
					$("p.questionnaireQuestionQCreditXtra").addClass("questionCross");
					$("#QCreditXtraHelp").show();
					incorrectAnswers++;
				}else{
					$("p.questionnaireQuestionQCreditXtra").addClass("questionTick");	
				}
				
				$("p.questionnaireButton").addClass("questionnaireButtonProceed");	
				
				//are there any wrong questions
				if (incorrectAnswers == 0){
				
					$(".questionnaireBubble").html("<h3>Thank you...</h3><p>Thank you for completing the questionnaire and helping us to improve. To proceed to 'My Lenders', click the button below.</p>");
				
				}else{
					
					if (incorrectAnswers == 1){
						var answersText = "answer";
					}else{
						var answersText = "answers";
					}
					
					$(".questionnaireBubble").html("<h3>Thank you...</h3><p>Thank you for helping us to improve. You got " + incorrectAnswers + " " + answersText + " wrong. The correct answers are shown below.</p>");
					
				}
				
				return false;
				
			}
			
		}
		
	});
	
	$.fn.getExistingDebts = function(){
		$.ajax({
			type: "POST",
			url: "/ajax/application/getExistingDebts.php",
			cache: false,
			dataType: "json",
			success: function(result){
						$.each(result,function(i,val){
							if(val.DebtType == 2){
								var newCol = '<div class="refused-creditors-column1 '+val.DebtID+' ">'+val.CreditorName+'</div><div class="refused-creditors-column2 '+val.DebtID+' "><a href="#" class="remove" name="'+val.DebtID+'" >remove</a></div><br class="'+val.DebtID+'" />';
								$("#refused-creditors-column").append(newCol);
							}else if(val.DebtType == 4){
								var newCol = '<div class="current-creditors-column1 '+val.DebtID+' ">'+val.CreditorName+'</div><div class="current-creditors-column2 '+val.DebtID+' "><a href="#" class="remove" name="'+val.DebtID+'" >remove</a></div><br class="'+val.DebtID+'" />';
								$("#current-creditors-column").append(newCol);
							}
						});
						
						$(".remove").click(function(){
							var remove = $(this).attr("name");
							$(this).removeDebt(remove);
							return false;
						});
					}
		});
						
		return false;				
	};
	
	$.fn.removeDebt = function(remove){			
		$.ajax({
			type:           "POST",
			url:            "/ajax/application/removeDebt.php",
			data:			"tempid="+remove,
			cache:          false,
			success:        function(result){
								if(result != "fail"){
									$("." + remove).remove();
								}
							}
		});
		
		return false;
	};
	
	
	$.fn.addDebt = function(type,name){
				
		if(name.length > 0){
			
			$.ajax({
				type:           "POST",
				url:            "/ajax/application/addDebt.php",
				data:			"type="+type+"&name="+name,
				cache:          false,
				success:        function(result){

									if((result.length > 0)&&(result != "fail")){
										if(type == 2){
											$("#refused-creditors-column").append("<div class=\"refused-creditors-column1 " + parseInt(result) + "\">"+name+"</div><div class=\"refused-creditors-column2 " + parseInt(result) + " \"><a href=\"#\" class=\"remove\" name=\"" + parseInt(result) + "\">remove</a></div><br class=\"" + parseInt(result) + "\" />");
											$(".applicationForm input[name=lendersAJAX]").val("");
										}else{
											$("#current-creditors-column").append("<div class=\"current-creditors-column1 " + parseInt(result) + "\">"+name+"</div><div class=\"current-creditors-column2 " + parseInt(result) + " \"><a href=\"#\" class=\"remove\" name=\"" + parseInt(result) + "\">remove</a></div><br class=\"" + parseInt(result) + "\" />");
											$(".applicationForm input[name=creditorsAJAX]").val("");
										}
									}
									
									$(".remove").click(function(){
										var remove = $(this).attr("name");
										$(this).removeDebt(remove);
										return false;
									});					
									
								}
			});
		}	
	};
	
	$.fn.addCreditCard = function(strCreditCard, intCardID) {
		
		if (strCreditCard.length > 0) {	

			if ($("#creditCardsColumn:contains('" + strCreditCard + "')").length == 0) {
				$.ajax({
					type:           'POST',
					url:            '/ajax/application/addReqCreditCard.php',
					data:			'cardID=' + parseInt(intCardID) + '&cardName=' + strCreditCard,
					cache:          false,
					success:        
						function(result) {

							//if (result.length > 0 && result == 'OK') {

								$('#creditCardsColumn').append(
									'<div class="creditCardsColumn1 creditCardItem' + strCreditCard.split(' ').join('') + '">' + strCreditCard + '</div>' + 
									'<div class="creditCardsColumn2 creditCardItem' + strCreditCard.split(' ').join('') + '">' + 
									'<a href="#">remove</a>' +
									'</div>' +
									'<br class="creditCardItem' + strCreditCard.split(' ').join('') + '" />');
								
								$('.creditCardItem' + strCreditCard.split(' ').join('') + ' A').click(function(){
									$(this).removeCreditCard(strCreditCard, intCardID);
									
									return false;
								});
							//}
						}
				});
			} else {
			    $.ajax({
					type:           'POST',
					url:            '/ajax/application/addReqCreditCard.php',
					data:			'cardID=0&cardName=' + strCreditCard,
					cache:          false,
					success:        function(result){}
				});
			}
		}
	};
	
	$.fn.removeCreditCard = function(strCreditCard, intCardID) {

		if (strCreditCard.length > 0) {	
			$.ajax({
				type:           'POST',
				url:            '/ajax/application/removeReqCreditCard.php',
				data:			'cardID=' + parseInt(intCardID) + '&cardName=' + strCreditCard,
				cache:          false,
				success:        
					function(result) {
				
						//if (result.length > 0 && result == 'OK') {
							$('.creditCardItem' + strCreditCard.split(' ').join('')).remove();
						//}
					}
			});
		}
	};

	$.fn.addBankAccount = function(strBankAccount, intBankID) {
		
		if (strBankAccount.length > 0) {	

			if ($("#bankAccountsColumn:contains('" + strBankAccount + "')").length == 0) {
				$.ajax({
					type:           'POST',
					url:            '/ajax/application/addReqBankAccount.php',
					data:			'bankID=' + parseInt(intBankID),
					cache:          false,
					success:        
						function(result) {

							//if (result.length > 0 && result == 'OK') {

								$('#bankAccountsColumn').append(
									'<div class="bankAccountsColumn1 bankAccountItem' + intBankID + '">' + strBankAccount + '</div>' + 
									'<div class="bankAccountsColumn2 bankAccountItem' + intBankID + '">' + 
									'<a href="#">remove</a>' +
									'</div>' +
									'<br class="bankAccountItem' + intBankID + '" />');
								
								$('.bankAccountItem' + intBankID + ' A').click(function(){
									$(this).removeBankAccount(strBankAccount, intBankID);
									
									return false;
								});
							//}
						}
				});
			}
		}
	};
	
	$.fn.removeBankAccount = function(strBankAccount, intBankID) {

		if (strBankAccount.length > 0) {	
			$.ajax({
				type:           'POST',
				url:            '/ajax/application/removeReqBankAccount.php',
				data:			'bankID=' + parseInt(intBankID),
				cache:          false,
				success:        
					function(result) {
				
						//if (result.length > 0 && result == 'OK') {
							$('.bankAccountItem' + intBankID).remove();
						//}
					}
			});
		}
	};
	
	$.fn.highLightErrors = function(){
		
		$(".formSection .formElement").each(function(i,val){
			if($(this).find("span.err").text().length > 0){
				$(this).css("background-color","#dbf6fe");
				$(this).css("border","1px solid #5fceea");
				$(this).css("padding","2px");
				$(this).css("margin-right","20px");
			}
		});
		
		
		if($(".formSection .formElement span.err").length > 0){
			$(".formSection .formElement span.err").fadeOut(350)
												   .fadeIn(350)
												   .fadeOut(350)
												   .fadeIn(350);
		}
		
		return;
	};
	
	// Always show the 'standard' action button when a payment date has not been specified. 
	$('#payDropSelect').change(function() {
		if ($('#FutureDate').val() == '-1') {
			$('#newFormPaymentNext').show();
		}
	});
	
	//Bind enter button to find address link in old app form
	$(".applicationForm .formSection .formElementSeperator #PostCode").bind("keypress", function(e) {
		if(e.keyCode == 13){
				$('#fetchAddress input').click();
				return false;
			}
		});	

	if(!bypassAddressFinder && $(".applicationForm .formSection .formElementSeperator #PostCode").length > 0){
				
		if
			(($("input[name=Address1]").val().length == 0)
			&&
			($("input[name=Address2]").val().length == 0)
			&&
			($("input[name=Town]").val().length == 0)
			&&
			($("input[name=Address1]").parent().find("span.err").length == 0)
			&&
			($("input[name=Address2]").parent().find("span.err").length == 0)
			&&
			($("input[name=Town]").parent().find("span.err").length == 0))
		{
			$("input[name=Address1]").parent().show();
			$("input[name=Address2]").parent().show();
			$("input[name=Town]").parent().show();
		}
		
		$(".newFormAddress1").hide();
		$(".newFormAddress2").hide();
		$(".newFormTown").hide();
		
		if ($("#PostCode").val().length > 0){
			$(".newFormAddress1").show();
			$(".newFormAddress2").show();
			$(".newFormTown").show();
		}

		$(".formSection .formElementSeperator #PostCode").css("width","108px");
		
		$("a.findAdd").die("keypress").live("keypress", function(e) {
    	if (e.which == 32) {
        	$('#fetchAddress a').click();
        	e.preventDefault();
    	}
});		

		if (!bypassAddressFinder)
		{
			$("#fetchAddress").append("<input type=\"submit\" class=\"findAdd find-address-button\" value=\"&nbsp;\" /><div id=\"postcodeLoader\"></div>");
	
			$("#postcodeLoader").hide();
			
			$('#fetchAddress input').click(function() {
				
				var postCode = $('#PostCode').val();
				
				if(postCode != 0){
					
					//show loader
					$("#postcodeLoader").show();
					
					$.ajax({
						type:           "POST",
						url:            "/ajax/application/fetchAddressList.php",
						dataType:       "json",
						cache:          false,
						data:           "postCode="+postCode,
						success:        function(json){
											if(json != '') {
												
												var select = '<select id="selectAddress" class="postCodeDropdown dropDownVali"><option selected="selected" value="0">Please select an address</option><option value="0">My address isn\'t here</option>';
												
												select += '<option value="0">-----------------------</option>';
												jQuery.each(json, function(i, value) {
													/*value = value.replace(postCode.toUpperCase(),"");*/
													value = value.substring((postCode.length + 1));
													select += '<option value="'+i+'">'+$.trim(value)+'</option>';
	
													});
												
												select += '<option value="0">-----------------------</option>';
												select += '<option value="0">My address isn\'t here</option>';	
												
												select += '</select>';
												
												if($('#selectAddresses select')){
													/*$('#selectAddresses').slideUp("slow");*/
													$('#selectAddresses').children().remove();
												}
												
												$('#selectAddresses').append(select);
												$('#selectAddresses').slideDown("fast");
												$('#selectAddresses').show();
																																		
												//$(".newFormAddress1").slideDown("fast");
												//$(".newFormAddress2").slideDown("fast");
												//$(".newFormTown").slideDown("fast");
												
												$("#cantFind").click(function(){
													$("input[name=Address1]").parent().slideDown("slow");
													$("input[name=Address2]").parent().slideDown("slow");
													$("input[name=Town]").parent().slideDown("slow");
													$("#selectAddresses").slideUp("slow");
													$("#selectAddress").remove();
													return false;
												});
												
												$('#selectAddress').change(function() {
													
													if($(this).val() != 0){
													
														var value = $("#selectAddress :selected").text();
														var address = value.split(",");
														
														if(address[3]){
															$("input[name=Address1]").val($.trim(address[0]+' '+address[1]));
															$("input[name=Address2]").val($.trim(address[2]));
															$("input[name=Town]").val($.trim(address[3]));
														}
														else if(address[2]){
															$("input[name=Address1]").val($.trim(address[0]));
															$("input[name=Address2]").val($.trim(address[1]));
															$("input[name=Town]").val($.trim(address[2]));
														}else{
															$("input[name=Address1]").val($.trim(address[0]));
															$("input[name=Address2]").val('');
															$("input[name=Town]").val($.trim(address[1]));
														}		
														
														$(".newFormAddress1").slideDown("fast");
														$(".newFormAddress2").slideDown("fast");
														$(".newFormTown").slideDown("fast");
														
														$('#selectAddresses').slideUp("slow");
														
													}else{
													
														$(".newFormAddress1").slideDown("fast");
														$(".newFormAddress2").slideDown("fast");
														$(".newFormTown").slideDown("fast");
														
													}
																							
												});
												
											} else {
												$('#selectAddresses').slideUp('normal', function() {
													
													alert('No addresses found for the post code "'+postCode+'". Please revise or enter your address manually.');
													$(".newFormAddress1").slideDown("fast");
													$(".newFormAddress2").slideDown("fast");
													$(".newFormTown").slideDown("fast");
												});
											}
											
											$("#postcodeLoader").hide();
											
										}
										
										
										
					});
					
				}else{
					alert("Please enter your postcode into the postcode field.");
					$('#PostCode').focus();
				}
		
				return false;
			});
		}
	}
	
	/*
		// Show/hide the direct debit and bank account questions depending on the
		// answer of the debit/credit card question.
		// TODO: Remove half of this code once split test is complete.
		var strBankAccountParentClass = $('INPUT[name=BankAccount]').parent().attr('class');
		
		// If 'No' is clicked and after submission the questions haven't been answered then show them both.
		if ($('INPUT[name=DebitCreditCard][value=0]').attr('checked') != true)
		{
			if (strBankAccountParentClass != null && strBankAccountParentClass.indexOf('formElementSeperator') > -1)
			{
				$('INPUT[name=BankAccount]').parent().hide();
				$('INPUT[name=DirectDebit]').parent().hide();
			}
			else
			{
				$('INPUT[name=BankAccount]').parent().parent().hide();
				$('INPUT[name=DirectDebit]').parent().parent().hide();
			}
		}
		
		// If 'Yes' is clicked, hide the two other questions but pre-select their values.
		$('INPUT[name=DebitCreditCard][value=1]').click(function() 
		{
			$('INPUT[name=BankAccount][value=1]').attr('checked', true);
			$('INPUT[name=DirectDebit][value=1]').attr('checked', true);
			
			if (strBankAccountParentClass != null && strBankAccountParentClass.indexOf('formElementSeperator') > -1)
			{
				$('INPUT[name=BankAccount]').parent().hide();
				$('INPUT[name=DirectDebit]').parent().hide();
			}
			else
			{
				$('INPUT[name=BankAccount]').parent().parent().hide();
				$('INPUT[name=DirectDebit]').parent().parent().hide();
			}		
		});
		
		// If 'No' is clicked, show the two other questions non pre-selected.
		$('INPUT[name=DebitCreditCard][value=0]').click(function() {
			$('INPUT[name=BankAccount]').attr('checked', false);
			$('INPUT[name=DirectDebit]').attr('checked', false);
			
			if (strBankAccountParentClass != null && strBankAccountParentClass.indexOf('formElementSeperator') > -1)
			{
				$('INPUT[name=BankAccount]').parent().show();
				$('INPUT[name=DirectDebit]').parent().show();
			}
			else
			{
				$('INPUT[name=BankAccount]').parent().parent().show();
				$('INPUT[name=DirectDebit]').parent().parent().show();
			}
		});
		*/

		$("#newFormPaymentNext").show();
		$(".applicationForm .payIntro").hide();
		$(".applicationForm div.whenPay").hide();
		
		//Hide, show or populate relevant direct debit payment elements		
		$("h2.ddPay").html("Ok, you want to pay by Direct Debit");
		$("div.ddPay").hide();
		$(".ddEditSubmit").hide();
		$("div.ddCheck").hide();
		$("div.ddInfo").hide();
		$(".applicationForm .newDDInfo").hide();
		$("#ddConfirm").hide();
		$("#ddCheckBoxDiv").hide();
		$("#ddReConfCheckBoxDiv").hide();
		$("#ddContReconf").hide();
		$(".CXnewDDInfo").hide();
		$(".cxSubmit").hide();
		$("#CXContReconf").show();
		$("#addCXTop").show();
		
		//Hide, show or populate relevant credit card payment elements
		$(".applicationForm div.cardPay").hide();
		$("div#ddEditSubmit").hide();
		$(".applicationForm .ccNext").hide();

		//Show the date select drop down if payment method has been selected
		if($('#payDropSelect').val() != -1)
		{
			$('div.newSelect').show();
		}
		
		if( $('p.err').is(':visible') ) {
			$(".applicationForm div.whenPay").show();
		}

		if($(".applicationForm select[name=FutureDate]").val() == -1){
			$("#ddPay").hide();
			$(".applicationForm #cardPay").hide();
		}
		
		if(($("input[name=selectPay]:radio:checked").val() == 1) && ($(".applicationForm select[name=FutureDate]").val() !== -1))
		{
			$(".applicationForm div.cardPay").show();
			$(".applicationForm .ccNext").show();
		}else if(($("input[name=selectPay]:radio:checked").val() == 0) && ($(".applicationForm select[name=FutureDate]").val() !== -1))
		{
			$(".applicationForm div.ddPay").show();
			$(".applicationForm div.ddInfo").show();
			//$(".applicationForm div.newDDInfo").show();
			$(".applicationForm .ddCont").show();
			
			var collectDate = $("#FutureDate :selected").text();
			var dateCheckArray = collectDate.split('(');
			if((dateCheckArray).length > 1){
				var collectDateSplitArray = dateCheckArray[1].split(')');
				var cxDateSplitArray = collectDateSplitArray[0].split('/');
				CXDateCheck(cxDateSplitArray[0]+"."+cxDateSplitArray[1]+"."+cxDateSplitArray[2]);
			}
		}
		
		if($("#payDropSelect").val() == 0){
			$(".applicationForm .whenPay").show();
		}
		
		if(($("#payDropSelect").val() === 1) && ($(".applicationForm select[name=FutureDate]").val() !== -1))
		{
			$(".applicationForm div.cardPay").show();
			$(".applicationForm .ccNext").show();
			$("#newFormPaymentNext").hide();
		} else if(($("#payDropSelect").val() == 0) && ($(".applicationForm select[name=FutureDate]").val() !== -1))
		{
			$(".applicationForm div.ddPay").show();
			$(".applicationForm div.ddInfo").show();
			//$(".applicationForm div.newDDInfo").show();
			$(".applicationForm .ddCont").show();
			$("#newFormPaymentNext").hide();
		}
		
		//$("#newFormPaymentNextButton").click(function(){
		$("#newFormPaymentNext").click(function(){
			
			if($("#payDropSelect").val() == -1)
			{
				$(".selectMethodError").html("Please select how you would like to make your payments");
			}
			if($("#FutureDate").val() == -1)
			{
				$(".selectDateError").html("Please select your preferred payment date");
			}
			return false;
		});

		$("input[name=selectPay]").click(function()
		{
			if($(this).val() == 1){
				$(".applicationForm div.ddInfo").slideUp();
				$(".applicationForm div.newDDInfo").slideUp();
				$(".applicationForm .ddCont").hide();
				$(".applicationForm div.ddPay").slideUp("slow",function(){
					if($(".applicationForm select[name=FutureDate]").val() != -1){
						$(".applicationForm div.cardPay").slideDown("slow");
						$(".applicationForm .ccNext").show();
						$(".applicationForm .ddPay input").each(function(i,val){
							if (this.type != "submit"){
								$(this).val('');
							}
							$(this).parent().find("span.err").text('');
						});
					}
				});
			}
			else if($(this).val() == 0)
			{
				$(".applicationForm .ccNext").hide();
				$(".applicationForm div.cardPay").slideUp("slow",function(){
					if($(".applicationForm select[name=FutureDate]").val() != -1)
					{
						$(".applicationForm div.ddPay").slideDown("slow");
						$(".applicationForm div.ddInfo").slideDown("slow");
						$(".applicationForm div.newDDInfo").slideDown("slow");
						$(".applicationForm .ddCont").show();
						
						$(".applicationForm .cardPay input").each(function(i,val)
						{
							if (this.type != "submit"){
								$(this).val('');
							}
						});
					}
				});
			}
		});
		
		$("select[name=FutureDate]").change(function(){
		
			if(($("#payDropSelect").val() == -1) || ($("#FutureDate").val() == -1)){
			if($("#payDropSelect").val() == -1)
			{
				$(".selectMethodError").html("Please select how you would like to make your payments");
			}
			if($("#FutureDate").val() == -1)
			{
				$(".selectDateError").html("Please select your preferred payment date");
			}
		}else{
			
				$(".selectMethodError").html(" ");
				$(".selectDateError").html(" ");
				$("#newFormPaymentNext").hide();
				
				//Customer has chosen debit/credit card
				if(($(this).val() !== -1)&&(($("input[name=selectPay]:radio:checked").val() == 1)||($("#payDropSelect").val() == 1)))
				{
					$(".applicationForm div.ddPay").slideUp("slow");
						$(".applicationForm div.cardPay").slideDown("slow");
						$(".applicationForm .ccNext").slideDown("slow");
						$(".applicationForm .ddPay input").each(function(i,val){
							if (this.type != "submit"){
								$(this).val('');
							}
							$(this).parent().find("span.err").text('');
						});
				
				}else{
					//The customer must have chosen direct debit
					$(".applicationForm .ccNext").hide();
					$(".applicationForm div.cardPay").slideUp("slow",function(){
						$(".applicationForm div.ddPay").slideDown("slow");
						$(".applicationForm div.ddInfo").slideDown("slow");
						$("#ddCheckBoxDiv").slideDown("slow");
						
						//$(".applicationForm div.newDDInfo").slideDown("slow");
						
						$(".applicationForm .ddCont").show();
	
						var collectDate = $("#FutureDate :selected").text();
						var dateCheckArray = collectDate.split('(');
						var collectDateSplitArray = dateCheckArray[1].split(')');
						
						
						var cxDateSplitArray = collectDateSplitArray[0].split('/');
						CXDateCheck(cxDateSplitArray[0]+"."+cxDateSplitArray[1]+"."+cxDateSplitArray[2]);
						
						$(".applicationForm .cardPay input").each(function(i,val){
							if (this.type != "submit"){
								$(this).val('');
							}
						});
					});
				}
			}
		});
		
		if($("select[name=FutureDate]").val() != -1){
				$("select[name=FutureDate]").change();
			}

		$(".applicationForm input[name=selectPay]").click(function(){
			if(($(this).val() !== 1)||($(this).val() !== 0))
			{
				$(".applicationForm .whenPay").slideDown("slow");
			}else{
				$(".applicationForm .whenPay").slideUp("slow");
			}
		});
		
		$("#payDropSelect").change(function(){
			if(($(this).val() == 1)||($(this).val() == 0)){
				$(".applicationForm .whenPay").slideDown("slow");
			}else{
				$(".applicationForm .whenPay").slideUp("slow");
				
				$(".applicationForm div.ddPay").slideUp();
				$(".applicationForm .ddCont").hide();
				$("#ddCheckBoxDiv").hide();		
	
				$(".applicationForm .ccNext").hide();
				$(".applicationForm div.cardPay").slideUp();
			}

			$(".selectMethodError").html(" ");
			$(".selectDateError").html(" ");
			
			if($(this).val() == 1){
				$(".applicationForm div.ddInfo").slideUp();
				$(".applicationForm div#ddCheckBoxDiv").slideUp();
				$(".applicationForm div.newDDInfo").slideUp();
				$(".applicationForm .ddCont").hide();
				$("select#FutureDate option[value=10]").show();
				$(".applicationForm div.ddPay").slideUp("slow",function(){
					if($(".applicationForm select[name=FutureDate]").val() != -1){
						$(".applicationForm div.cardPay").slideDown("slow");
						$(".applicationForm div.cardInfo").slideDown("slow");
						$(".applicationForm .ccNext").show();
						$('p.err, span.err').hide();
						
						$(".applicationForm .ddPay input").each(function(i,val){
							if (this.type != "submit"){
								$(this).val('');
							}
							$(this).parent().find("span.err").text('');
						});
					}
				});
			}else if($(this).val() == 0){
				//Hide the last friday of the month if the customer has chosen direct debit
				if($("select#FutureDate").val() == 10)
					{
						$("select#FutureDate").val(-1);
					}
				$("select#FutureDate option[value=10]").hide();
				
				$(".applicationForm .ccNext").hide();
				$(".applicationForm div.cardInfo").slideUp("slow");
				$(".applicationForm div.cardPay").slideUp("slow",function(){
					
					if($(".applicationForm select[name=FutureDate]").val() != -1){
					$(".applicationForm div#ddCheckBoxDiv").slideDown();
					$(".applicationForm div.ddPay").slideDown("slow");
					$(".applicationForm div.ddInfo").slideDown("slow");
					//$(".applicationForm div.newDDInfo").slideDown("slow");
					$(".applicationForm .ddCont").show();
					$('p.err, span.err').hide();

					$(".applicationForm .cardPay input").each(function(i,val){
						if (this.type != "submit"){
							$(this).val('');
						}
					});
					}
				});
			}
		});
		
		$('a#ddEdit').click(function() {
			//Show
			$(".applicationForm div.FutureDate").slideDown("slow");
			$(".applicationForm div.selectPay").slideDown("slow");
			$(".applicationForm div.repayments").slideDown("slow");
			$(".applicationForm div.whenPay").slideDown("slow");
			$(".applicationForm .ddCont").slideDown("slow");
			$('.applicationForm input[name=ddCont]').show();
			$('.applicationForm .ddInfoMessage').show();
			$(".applicationForm div.ddPay").slideDown("slow");
			$("div.repayments").slideDown("slow");
			$("#newDDHidden").show("slow");
			$("#ddCheckBoxDiv").slideDown("slow");
			
			//Hide
			$(".applicationForm .ddEditSubmit").slideUp("slow");
			$(".applicationForm div.ddCheck").slideUp("slow");
			$("p.err").hide();
			$(".applicationForm .newDDInfo").slideUp("slow");
			$("#ddConfirm").hide("slow");
			$('a#ddEdit').hide();
			$("#ddReConfCheckBoxDiv").hide("slow");
			$(".ddEditHide").hide();
			$(".ddReconf").hide("slow");
			$("#ddContReconf").hide("slow");

			return false;
		});
		
		$("a#ddCXTop").click(function(){
			$("#ddCXCheck").slideDown("slow");
			$(".ddReconf").slideUp("slow");
			$(".ddEditSubmit").hide();
			$("input[name=ddContReconf]").show();
			$("#ddLFCheck").slideDown("slow");
			$("div#newDDHidden").show("slow");
			$("#ddConfirm").hide("slow");
			$("#cxCheckBoxDiv").slideDown("slow");

			return false;
		});

		$("#applyStageTwo").bind("keypress", function(e) {
			if(e.keyCode == 13){
				$('.applicationForm input[name=ddCont]').click();
				return false;
			}else{
				return true;
			}
		});
		

		//Function for 'next stage' button in direct debit application forms
	$('.applicationForm input[name=ddCont]').click(function() {
	if($("#ddCheckbox:checked").val() !== undefined){
		$("#newFormPaymentNext").click();
			//assign form fields to variables
		var accountName = $(".applicationForm #AccountName").val();
		var sortCode = $(".applicationForm #SortCode").val();
		var accountNo = $(".applicationForm #AccountNo").val();
		
		onlyNumbers = /[^1234567890]/ig; 
		sortCode = sortCode.replace(onlyNumbers, "");
		
			//Pass relevant variables into pre-submit js error checking
		var errors = checkddDetails(accountName, sortCode, accountNo);
		
			//if no errors, carry out ajax bank details check
		if (errors <1){
				bankCheckAjax(sortCode, accountNo, true, "LFStageTwo");
				var collectDate = $("#FutureDate :selected").text();
				var dateCheckArray = collectDate.split('(');
				var collectDateSplitArray = dateCheckArray[1].split(')');
				$("#dateCheck").html(collectDateSplitArray[0]);
			}
	}else{
		$("span#boxNoteTick").html("<span class='boxErr'>Please tick to confirm you are the account holder</span>");
		}
	return false;
	});
	
	
	
	$("input[name=ddContReconf]").click(function() {
		if (($("#stageTwoCX").length)&&($("#ddCheckbox:checked").val() == undefined)){
			$("span#boxNoteTick").html("<span class='boxErr'>Please tick to confirm you are the account holder</span>");
			window.location = "#headerTop";
			return;
		}
		$("div#newDDHidden").hide("slow");
		$("#ddCXCheck").slideUp("slow");
		$(".ddReconf").slideDown("slow");
		$(".ddEditSubmit").show();
		$("input[name=ddContReconf]").hide();
		$("#ddLFCheck").slideUp("slow");
		$(".cxConfirm").html('<img src="https://secure.loanfinder.co.uk/images/creditxtra/cx-logo.gif" alt="creditXtra Logo">');
		$("#ddConfirm").show("slow");
		$("#cxCheckBoxDiv").slideUp("slow");
		return false;
	});

	
	if($("#stageTwoCX").length){
		var accountName = $("#accountNameCX").val();
		var sortCode = $("#sortCodeCX").val();
		var accountNo = $("#accountNoCX").val();
		bankCheckAjax(sortCode, accountNo, false, "LFStageTwoCX");
		
		$("#ddCheckBoxDiv").hide("slow");
	}

	if ($("#ddCheckboxErr").length){
		if(!$(".nameError").length){
			window.location = "#ddCheckBoxDiv";
			$("select[name=FutureDate]").change();
			$('.applicationForm input[name=ddCont]').click();
		}
	}
		
	if ($('.applicationForm #bankAccounts')) {
		$(".applicationForm #bankAccounts textarea").hide();

		$(".applicationForm #bankAccountsField").append('<input class="formTextArea" id="bankAccountsAJAX" name="bankAccountsAJAX" type="input" />&nbsp;&nbsp;<input class="add-button debtsSubmit" id="bankAccountsAJAXButton" name="bankAccountsAJAXButton" type="button" value="&nbsp;"/>');	
			
		$("p.bankAccounts").text("We need to know which banks you currently have accounts with. Enter the name of each bank (for example 'Barclays Bank') in the box.");
	}
	
	if ($('.applicationForm #creditCards')) {
		$(".applicationForm #creditCards textarea").hide();

		$(".applicationForm #creditCardsField").append('<input class="formTextArea" id="creditCardsAJAX" name="creditCardsAJAX" type="input" />&nbsp;&nbsp;<input class="add-button debtsSubmit" id="creditCardsAJAXButton" name="creditCardsAJAXButton" type="button" value="&nbsp;"/>');	
			
		$("p.creditCards").text("We need to know which credit cards you currently own. Enter the name of each credit card (for example 'Capital One') in the box.");
	}

	if($(".applicationForm #lenders")){
		$(".applicationForm #lenders textarea").hide();
		
		$(".applicationForm .lenders").append("<input type=\"input\" name=\"lendersAJAX\" class=\"formTextArea\"/>&nbsp;&nbsp;<input type=\"button\" name=\"lendersAJAXButton\" class=\"add-button debtsSubmit\" value=\"&nbsp;\"/>");
	
		$("p.lenders").html("We need to know who you have been refused credit by. Enter the name of the company you were refused by (for example 'Barclays Loans') in the box.<br /><strong>Leave the box blank if you have not been refused credit.</strong>");
	}
	
	if($(".applicationForm #creditors")){
		$(".applicationForm #creditors textarea").hide();
		
		$(".applicationForm .creditors").append("<input type=\"input\" name=\"creditorsAJAX\" class=\"formTextArea\"/>&nbsp;&nbsp;<input type=\"button\" name=\"creditorsAJAXButton\" class=\"add-button debtsSubmit\" value=\"&nbsp;\"/>");
		
		$("p.creditors").html("We need to know who you have credit with. Enter the name of the company you have credit with (for example 'Barclays Loans') in the box.<br /><strong>Leave the box blank if you do not have any credit.</strong>");
	}

	if ($('#bankAccountsAJAX').length > 0) {
	
		$.ajax({
			type:           'POST',
			url:            '/ajax/application/getBankNames.php',
			dataType:       'html',
			cache:          false,
			success:        function(json) {

								if (json != null)
								{
									var data = eval(json);
									var options = {
										minChars: 0,
							            width: 310,
							            matchContains: false,
							            mustMatch: false,
							    		formatItem: function(row, i, max) {
							    			return row.Name;
							    		},
							    		formatMatch: function(row, i, max) {
							    			return row.Name + ' - ' + row.Value;
							    		},
							    		formatResult: function(row) {
							    			return row.Name;
							    		}
									};
									
									$('#bankAccountsAJAX').autocomplete(data, options);
									
									$('#bankAccountsAJAX').result(function(event, data, formatted) {
										var intBankID = parseInt(formatted.substring(formatted.indexOf('-') + 2));
										
										$(this).addBankAccount($(this).val(), intBankID);
										$(this).val('');
									});
									
									$('#bankAccountsAJAXButton').click(function() {
										$(this).addBankAccount($('#bankAccountsAJAX').val());
										return false;
									});
								}
							}
		});
	}

	if ($('#creditCardsAJAX').length > 0) {
	
		$.ajax({
			type:           'POST',
			url:            '/ajax/application/getCardNames.php',
			dataType:       'html',
			cache:          false,
			success:        function(json) {

								if (json != null)
								{
									var data = eval(json);
									var options = {
										minChars: 0,
							            width: 310,
							            matchContains: false,
							            mustMatch: false,
							    		formatItem: function(row, i, max) {
							    			return row.Name;
							    		},
							    		formatMatch: function(row, i, max) {
							    			return row.Name + ' - ' + row.Value;
							    		},
							    		formatResult: function(row) {
							    			return row.Name;
							    		}
									};
									
									$('#creditCardsAJAX').autocomplete(data, options);
									
									$('#creditCardsAJAX').result(function(event, data, formatted) {
										var intCardID = parseInt(formatted.substring(formatted.indexOf('-') + 2));
										
										$(this).addCreditCard($(this).val(), intCardID);
										$(this).val('');
									});
									
									$('#creditCardsAJAXButton').click(function() {
										$(this).addCreditCard($('#creditCardsAJAX').val());
										return false;
									});
								}
							}
		});
	}

	if($("#lenders").length > 0){
		
		$.ajax({
			type:           "POST",
			url:            "/ajax/application/getLendersLF.php",
			dataType:       "html",
			cache:          false,
			success:        function(json){
								/*$.each(json,function(i,val){
									if($.trim(val.lf_creditor_description).length > 1){
										creditors += $.trim(val.lf_creditor_description)+";";
									}	
								});*/
								creditors = json;
			
								var data = creditors.split(";");
								
								var options = {
										minChars: 0,
							            width: 310,
							            matchContains: true
								};
												
								$(".applicationForm input[name=lendersAJAX]").autocomplete(data,options);
								$(".applicationForm input[name=creditorsAJAX]").autocomplete(data,options);
								
								$(".applicationForm input[name=lendersAJAX]").result(function(){
									$(this).addDebt(2,$(this).val());
								});
								
								$(".applicationForm input[name=lendersAJAXButton]").click(function(){
									$(this).addDebt(2,$(".applicationForm input[name=lendersAJAX]").val());
									return false;
								});
								
								$(".applicationForm input[name=creditorsAJAX]").result(function(){
									$(this).addDebt(4,$(this).val());
								});
								
								$(".applicationForm input[name=creditorsAJAXButton]").click(function(){
									$(this).addDebt(4,$(".applicationForm input[name=creditorsAJAX]").val());
									return false;
								});
							}
		});
	}
	
	//Uncomment this if you want the fancy error message displays.
	//$(this).highLightErrors();
	if($("#lenders").length > 1){
		$(this).getExistingDebts();
	}
	
	//If we have the non-js textareas for both creditors and lenders then remove the content
	//from them.
	if($("textarea[name=Creditors]").length > 0){
		$("textarea[name=Creditors]").val('');
	}
	
	if($("textarea[name=Lenders]").length > 0){
		$("textarea[name=Lenders]").val('');
	}
	
	
		if ($(".withoutDD").val() == 1){
		$(".whenPay").show();
		$(".cardPay").hide();
			if($("#FutureDate").val() != -1){
				$(".cardPay").show();
			}
		
		}
	
	
	
});


	//This code control the modal pop on the first page of the app form
	$("#close").click(function(){
		hideModal('modalPage');
		
	});
	$("#close2").click(function(){
		hideModal('modalPage');
		
	});

	$(function(){
		if($("#modalPage").length > 0){
			popup('modalPage');
		}
	});

	//This function control make the modal pop appear
	function popup(modalPage)
	{
		 window.onscroll = function () { document.getElementById(modalPage).style.top = document.body.scrollTop; };
     	         document.getElementById(modalPage).style.display = "block";
   	         document.getElementById(modalPage).style.top = document.body.scrollTop;
	}
	//This function closes the modal pop

	function hideModal(modalPage)
	{
 	    document.getElementById(modalPage).style.display = "none";
	}

	$(document).ready(function()
		{
			$("#iva").click(function ()
			{
				$("#ivaText").toggle("slow");
			});
			$("#bankrupt").click(function ()
			{
				$("#bankruptText").toggle("slow");
			});
			$("#ccj").click(function ()
			{
				$("#ccjText").toggle("slow");
			});
			$("#default").click(function ()
			{
				$("#defaultText").toggle("slow");
			});

			$("#email").click(function ()
			{
				$("#emailText").toggle("slow");
			});
			
		/* Validation class highlights. */
		$("form.applicationForm .formSection .formElementSeperator, form.applicationForm .formSection .formElementSeperator2, .formElement").each(function(i,val) {
		
			var objLabel = $(this).find('label');

			if (objLabel != null && objLabel.hasClass('err'))
			{
				$(this).find('input, select').each(function(intIndex, objElement) {
					
					if (objElement.tagName == 'INPUT')
					{					
						var strElementType = $(objElement).attr('type');
						
						switch (strElementType)
						{
							case 'text':
							case 'password':	
								$(objElement).removeClass('formTextArea').addClass('formTextAreaError');
							break;	
							
							case 'select':
								$(objElement).removeClass('formDropDown').addClass('formDropDownError');
							break;	
				
							case 'radio':
								$(objElement).parent().find('i').removeClass('yesNoBlue').addClass('yesNoRed');
							break;	
						}
					}
					else
					{
						if ($(objElement).hasClass('formDropDownSmall')) 
						{
							$(objElement).removeClass('formDropDownSmall').addClass('formDropDownSmallError');
						}
						else 
						{
							$(objElement).removeClass('formDropDown').addClass('formDropDownError');
						}
					}
				});
			}
		});
		
		$(".newCardLink").click(function(){	
			if($("#CGSFormCardNotEntered").is(":visible")){
				$('#CGSFormCardNotEntered').hide('fast');
				$('#CGSFormCardEntered').show('fast');
				
				$('#CGSFormCardNotEntered').find("p.err").remove();
				$('#card_name').val('');
				$('#card_number').val('');
				$('#card_issue').val('');
				$('#card_cv2').val('');
				$('#card_start_m').val('');
				$('#card_start_y').val('');
				$('#card_end_m').val('');
				$('#card_end_y').val('');	
			} else {
				$('#CGSFormCardNotEntered').show('fast');
				$('#CGSFormCardEntered').hide('fast');
			}
		});		
			
	$("input.ccNext").click(function(){
		$("input#autoEmailID").val('DontSend');
		return true;
	});
		
		
	$("input#ddSubmit").click(function(){
		if($("#ddReCheckbox:checked").val() !== undefined){
			$("input#autoEmailID").val('DontSend');
			return true;
		}else{
			$("label#ReCheckLabel").html("<span class='boxErr'>Please confirm that these details are correct and that you are authorised to arrange Direct Debits from this account</span>");
			return false;
			}
	});
});
		
		
		function divShowHide(id,showhide)
		{
			if(showhide==1)
			{
				document.getElementById(id).style.display = "block";
			}
			else
			{
				document.getElementById(id).style.display = "none";
			}

		}
		
		
		function checkddDetails(accountName, sortCode, accountNo)
		{
		var errors = 0;
		
			$(".accNaErr").html("");
			$(".sortErr").html("");
			$(".accNoErr").html("");
			
		if ((accountName == "")||(sortCode == "")||(accountNo == ""))
		{	errors++;
			
			if(accountName == ""){
			$(".accNaErr").html("Please enter a valid account name");
			}
			
			if(sortCode == ""){
			$(".sortErr").html("Please enter a valid sort code");
			}
			
			if(accountNo == ""){
			$(".accNoErr").html("Please enter a valid account number");
			}
		}
		
		if (((!isNaN(accountName))||(accountName.length < 3))&&(accountName != "")){
			$(".accNaErr").html("The account name must be text and be at least three characters");
			errors++;
		}
		
		if ((sortCode.length != 6)&&(sortCode !="")){
			$(".sortErr").html("The sort code must consist of six numbers");
			errors++;
		}

		if (((isNaN(accountNo))||(accountNo.length < 8))&&(accountNo != "")){
			$(".accNoErr").html("The account number must consist of eight numbers");
			errors++;
		}
		
		if ($('#EmailAddressConfirm').val() == '') {
			//errors++;
			//alert('a');
		}
		
		if(errors >0){
				$("p.err").show();
				$("p.badSortAcc").hide();
				window.location = "#ddPayBox";
				}
				
				return errors;
		}
		
		function bankCheckAjax(sortCode, accountNo, ddSlide, callPage){
			$.ajax({
					type:		"POST",
					url:		"/ajax/getBankDetails.php",
					dataType:	"json",
					cache:		false,
					data: 		"sortCode="+sortCode+"&accountNo="+accountNo,
					success:	function(json){

						if (json === false){
								$("p.err").show();
								$("p.badSortAcc").html("Invalid Sort Code and/or Account Number");
								window.location = "#ddPayBox";
						}else{
								bankDets = json;
								var bankInfo = bankDets.split(",");
								var bankAddress = bankInfo[2]+", "+bankInfo[3]+", "+bankInfo[4];
								
									if (bankInfo[5] != undefined){
										bankAddress = bankAddress+", "+bankInfo[5];
										
										if (bankInfo[6] != undefined){
										bankAddress = bankAddress+", "+bankInfo[6];
										}
									}
									
								$("#bankNameCheck").html(bankInfo[1]);
								$("#bankBranchCheck").html(bankInfo[0]);
								$("#bankAddressCheck").html(bankAddress);
								
								$("td#reconfBankName").html(bankInfo[1]);
								
								$("#CXbankNameCheck").html(bankInfo[1]);
								$("#CXbankBranchCheck").html(bankInfo[0]);
								$("#CXbankAddressCheck").html(bankAddress);

								$("input#SortCode").val(sortCode);
								$("input#AccountNo").val(accountNo);
								
								if (ddSlide != false){
									ddSlideUp(callPage, sortCode);
									}
							}
						}
			});	
		}
		
		function ddSlideUp(callPage, sortCode){
		
			var accountName = ($("#AccountName").val());
			var accountNo = ($("#AccountNo").val());
			accountNoSplit = accountNo.split("");
			sortCodeSplit = sortCode.split("");
		
			$("#accountHolderCheck").html(accountName);
			$("td#ac1").html(accountNoSplit[0]);
			$("td#ac2").html(accountNoSplit[1]);
			$("td#ac3").html(accountNoSplit[2]);
			$("td#ac4").html(accountNoSplit[3]);
			$("td#ac5").html(accountNoSplit[4]);
			$("td#ac6").html(accountNoSplit[5]);
			$("td#ac7").html(accountNoSplit[6]);
			$("td#ac8").html(accountNoSplit[7]);
			
			$("td#sc1").html(sortCodeSplit[0]);
			$("td#sc2").html(sortCodeSplit[1]);
			$("td#sc3").html(sortCodeSplit[2]);
			$("td#sc4").html(sortCodeSplit[3]);
			$("td#sc5").html(sortCodeSplit[4]);
			$("td#sc6").html(sortCodeSplit[5]);
			
			$("td#reconfAcName").html(accountName);
			$("td#reconfAcNo").html(accountNo);
			$("td#reconfSortCode").html(sortCode);

			$("#CXaccountHolderCheck").html(accountName);
			$("#CXsortCodeCheck").html($("#SortCode").val());
			$("#CXaccountNoCheck").html($("#AccountNo").val());

			if (callPage === "paymentGuardApply") {
				$(".pgApplicationForm .noSpace").hide();
				$(".pgApplicationForm .ddCheck").slideDown("slow");
				$(".pgApplicationForm .ddPay").slideUp("slow");
				$(".pgApplicationForm #coverMe").show();
				$(".pgApplicationForm .ddCont").hide();
			}

			$(".ddContShow").show();
			$("#ddCheckBoxDiv").hide("slow");
			$("a#ddEdit").show();
			$("div.repayments").slideUp("slow");
			$("div.FutureDate").slideUp("slow");
			$("div.selectPay").slideUp("slow");
			$("div.repayments").slideUp("slow");
			$("div.whenPay").slideUp("slow");
			$("#ddCont").slideUp("slow");
			$('input[name=ddCont]').hide();
			$('.ddInfoMessage').hide();
			$("div.ddPay").slideUp("slow");
			$("input#ddContReconf").show();
			$("div.ddCheck").slideDown("slow");
			$("p.err").hide();
			$(".applicationForm .newDDInfo").slideDown("slow");
			$("#newDDHidden").hide("slow");
			$("#ddConfirm").html("<h2>Please confirm your Direct Debit</h2>");
			$("#ddConfirm").show("slow");
			$("#ddReConfCheckBoxDiv").slideDown("slow");
		}

		function CXDateCheck(paymentDate){
			$.ajax({
					type:		"POST",
					url:		"/ajax/checkCXPayDate.php",
					dataType:	"json",
					cache:		false,
					data: 		"paymentDate="+paymentDate,
					success:	function(json){
								cxPaymentDate = json;
								$("input#dateCheckCX").val(cxPaymentDate);
						}
			});
		}
				
		function hideModal(){
			$('div#modalPage').hide();
		}
		
		function sendImmediateNoP2PMail(stage, email, firstName, lastName, affiliate, CID, AID, Last3){
			$.ajax({
				url:		"/ajax/application/sendImmediateNoP2PMail.php",
				type: 		"POST",
				cache: 		false,
				async: 		false,
				data:		"stage="+stage+"&email="+email+"&firstName="+firstName+"&lastName="+lastName+"&affiliate="+affiliate+"&CID="+CID+"&AID="+AID+"&Last3="+Last3
			});
		}
		
		function setWidgetSession(){
			$.ajax({
				url:		"/ajax/lenders/setWidgetSession.php",
				async:		false
			});
		}
		
		function validateEmail(){
			email = $('input#EmailAddress').val();
			$.ajax({
				url: 		"/ajax/application/validateEmail.php",
				dataType:	"json",
				type: 		"POST",
				cache:		false,
				data:		"email="+email,
				success:	function(json){
							$("p#emailErr").hide();
							$("img#emailLoader").hide();
							if(json == true){
								$('input#EmailAddress').css("background-color","#FFFFFF");
								$('img#emailTick').show();
								$('p.emailAjaxErr').hide();
								$('input#emailAddressValid').val('true');
							}else{
								$('p.emailAjaxErr').html(json);
								$('p.emailAjaxErr').show();
								$('input#EmailAddress').css("background-color","#FFC0CB");
								$('img#emailCross').show();
								$('input#emailAddressValid').val('false');
							}
				}
			});
		}
		
		function getFeeAmount(MonthlyIncome, AmountRequired){
			$.ajax({
				url: 		"/ajax/application/getFeeAmount.php",
				dataType:	"json",
				type: 		"POST",
				cache:		false,
				data:		"MonthlyIncome="+MonthlyIncome+"&AmountRequired="+AmountRequired,
				success:	function(json){
						$("div#NoPaymentAmount").hide();
						$("div#YesPaymentAmount").show();
						
						$("span#st1Fee").html("&pound;"+json);
				}
			});
			
		}
