/**
FILENAME: application.js
AUTHOR: Ashley Barrett (ashley.barrett@rgroup.co.uk)
CREATED: 03/03/2010
COMMENTS: The javascript file for the new applicatiom form
UPDATE: Atti: Added divShowHide for payment guard form
UPDATE: Ashley Barrett (05/07/2010) Added in ajax functionality to get existing debts for customer updates.
UPDATE: Ashley Barrett (06/07/2010) Fix to stop every page trying to get the existing debts.
UPDATE: Chris Cheshire (26/07/2010) Updates to stage two elements for new direct debit page and implementation of print page link
UPDATE: Chris Cheshire (24/08/2010) Bind enter button to find address button or link only in postcode box
UPDATE: Crandy (31/08/2010) Removed the default value for salary
*/
$(function(){
	
	$('a.printPage').prepend('<a href="#print">Click here to print a copy of this page</a>');
	$('a.printPage a').click(function() {
		window.print();
		return false;
	});

	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.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;
	}
	
	//Bind enter button to find address link in old app form
	$(".applicationForm .formSection .formElementSeperator #PostCode").bind("keypress", function(e) {
		if(e.keyCode == 13){
				$('#fetchAddress a').click();
				return false;
			}
		});	

	
	if($(".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();
    	}
});		
		$("#fetchAddress").append("<input type=\"button\" class=\"findAdd\" value=\"Find Address\" /><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"><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();
		$("input#ddEdit").show();
		
		//Hide, show or populate relevant credit card payment elements
		$(".applicationForm div.cardPay").hide();
		$("div#ddEditSubmit").hide();
		$("div.ddCheck").hide();
		$("div.ddInfo").hide();
		$("#ddEdit").show();
		$(".applicationForm .ccNext").hide();
		
		
		
		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 .ddCont").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 .ddCont").show();
			$(".newFormPaymentNext").hide();
		}
		
		$("#newFormPaymentNextButton").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.");
			}
			
		});

		$("input[name=selectPay]").click(function(){
						
			if($(this).val() == 1){
				$(".applicationForm div.ddInfo").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().css("background-color","#fff");
						//$(this).parent().css("border","none");
						$(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 .ddCont").show();

					$(".applicationForm .cardPay input").each(function(i,val){
						if (this.type != "submit"){
							$(this).val('');
						}
					});
					}
				});
			}	
		});
		
		$("select[name=FutureDate]").change(function(){
			
			$(".selectMethodError").html(" ");
			$(".selectDateError").html(" ");
			$(".newFormPaymentNext").hide();
			if(($(this).val() !== -1)&&(($("input[name=selectPay]:radio:checked").val() == 1)||($("#payDropSelect").val() == 1))){
				$(".applicationForm div.ddPay").slideUp("slow",function(){
					$(".applicationForm div.cardPay").slideDown("slow");
					$(".applicationForm .ccNext").slideDown("slow");
					$(".applicationForm .ddPay input").each(function(i,val){
						if (this.type != "submit"){
							$(this).val('');
						}
						//$(this).parent().css("background-color","#fff");
						//$(this).parent().css("border","none");
						$(this).parent().find("span.err").text('');
					});
				});
			}else{
				$(".applicationForm .ccNext").hide();
				$(".applicationForm div.cardPay").slideUp("slow",function(){
					$(".applicationForm div.ddPay").slideDown("slow");
					$(".applicationForm div.ddInfo").slideDown("slow");
					$(".applicationForm .ddCont").show();

					$(".applicationForm .cardPay input").each(function(i,val){
						if (this.type != "submit"){
							$(this).val('');
						}
					});
				});
			}
		});

		$(".applicationForm input[name=selectPay]").click(function(){
			if(($(this).val() !== 1)||($(this).val() !== 0))
			{
				$(".applicationForm .whenPay").slideDown("slow");
			}else{
				$(".applicationForm .whenPay").slideUp("slow");
			}
		});
		
		//============This is for the payment select box split text==============//
		
		$("#payDropSelect").change(function(){
			if(($(this).val() == 1)||($(this).val() == 0)){
				$(".applicationForm .whenPay").slideDown("slow");
			}else{
				$(".applicationForm .whenPay").slideUp("slow");
			}
		});
		
		$("#payDropSelect").change(function(){
			$(".selectMethodError").html(" ");
			$(".selectDateError").html(" ");
			if($(this).val() == 1){
				$(".applicationForm div.ddInfo").slideUp();
				$(".applicationForm .ddCont").hide();
				$(".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();
						$('.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){
				$(".applicationForm .ccNext").hide();
				$(".applicationForm div.cardInfo").slideUp("slow");
				$(".applicationForm div.cardPay").slideUp("slow",function(){
					
					if($(".applicationForm select[name=FutureDate]").val() != -1){
					$(".applicationForm div.ddPay").slideDown("slow");
					$(".applicationForm div.ddInfo").slideDown("slow");
					$(".applicationForm .ddCont").show();
					$('.err').hide();

					$(".applicationForm .cardPay input").each(function(i,val){
						if (this.type != "submit"){
							$(this).val('');
						}
					});
					}
				});
			}
			//$(".newFormPaymentNext").hide();
		});
		
		//================================================================//
		
		$('#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");
			
			//Hide
			$(".applicationForm .ddEditSubmit").slideUp("slow");
			$(".applicationForm div.ddCheck").slideUp("slow");
			$("p.err").hide();
		});

		$("#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() {
			
				//assign form fields to variables
			var accountName = $(".applicationForm #AccountName").val();
			var sortCode = $(".applicationForm #SortCode").val();
			var accountNo = $(".applicationForm #AccountNo").val();
			
				//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]);
				}
	}); 
		
		
		
		
		
	if ($('.applicationForm #bankAccounts')) {
		$(".applicationForm #bankAccounts textarea").hide();
		$(".applicationForm #bankAccountsField").append('<input class="formTextArea" id="bankAccountsAJAX" name="bankAccountsAJAX" type="input" />&nbsp;&nbsp;<input class="submit debtsSubmit" id="bankAccountsAJAXButton" name="bankAccountsAJAXButton" type="button" value="Add"/>');
		$("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 #lenders")){
		$(".applicationForm #lenders textarea").hide();
		$(".applicationForm .lenders").append("<input type=\"input\" name=\"lendersAJAX\" class=\"formTextArea\"/>&nbsp;&nbsp;<input type=\"button\" name=\"lendersAJAXButton\" class=\"submit debtsSubmit\" value=\"Add\"/>");
		$("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=\"submit debtsSubmit\" value=\"Add\"/>");
		$("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());
									});
								}
							}
		});
	}
	
	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());
								});
								
								$(".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());
								});
							}
		});
	}
	
	//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('');
	}	
});


	//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").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');
				
				$('#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');
				
				$('#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('');			
			}
		});		
			
			
		});
		
		
		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(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);
								if (ddSlide != false){
									ddSlideUp(callPage);
									}
							}
						}
			});	
		}
		
		function ddSlideUp(callPage){
					$("#accountHolderCheck").html($("#AccountName").val());
					$("#sortCodeCheck").html($("#SortCode").val());
					$("#accountNoCheck").html($("#AccountNo").val());
					
					if (callPage ==="paymentGuardApply") {
						$(".pgApplicationForm .noSpace").hide();
						$(".pgApplicationForm .ddCheck").slideDown("slow");
						$(".pgApplicationForm .ddPay").slideUp("slow");
						$(".pgApplicationForm #coverMe").show();
						$(".pgApplicationForm .ddCont").hide();
					}

					$("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");
					$(".ddEditSubmit").slideDown("slow");
					$("div.ddCheck").slideDown("slow");
					$("p.err").hide();
				}
		
		
		
		
		
		
		
		