/**
 * Direct debit handles for regular giving donation
 **/
var errorMessagePrefix = "Please correct the following errors";
var errorMessage = "<div style=\"color:#f00;margin:1em 0;\"><strong>Please correct the information in the fields below.</strong></div>";
var branchdetails = {};
var bankvalid = true;

// Checks the bank details are valid, function checkForm must exist for finishing the checking.
function checkBankDetails(accNo, sortCode) {
	var bankwizardreached = function(json) {
		if (!json.validated) {
			// errorMessage = "<li>Bank details are invalid, please check account number and sort code</li>";
			bankvalid = false;
		}
		if (json.branchdetails) {
			bankvalid = true;
			errorMessage = "";
			branchdetails = json.branchdetails;
			// confirmdetails["bankname"] = branchdetails.bankname;
			$("#step2 span#bankName_answer").html(branchdetails.bankname);
		}
		checkForm();// continue with rest of checking
	};

	// unable to connect with the bank wizard system
	var bankwizardfailed = function() {
		checkForm();// continue with rest of checking
	};

	// ajax request using jQuery
	$.ajax({
		url: "/bankwizard/check.php?sc=" + sortCode + "&an=" + accNo,
		dataType: "json",
		success: bankwizardreached,
		error: bankwizardfailed
	});
} // end checkBankDetails


function displayConfirmation() {
	// clear error messages
	$("#formErrors").html("");
	$("#step2").hide();

	$("#resourcebox-bottom").show();

	// get all the field values and populate the confirmation section
	if ($("#q56550_q14_0").attr("checked") == true) {
		$("#step3 span#ddType").html("Start a new regular monthly gift");
	} else {
		$("#step3 span#ddType").html("Update an existing regular monthly gift");
	}

	if ($("#q56550_q13_0").attr("checked") == true) {
		$("#giftaid_answer").html("Yes");
	} else {
		$("#giftaid_answer").html("No");
	}

	$("#step3 span#bankName_answer").html(branchdetails.bankname);
	$("#step3 span#confirmAmount").html($("#q56550_q12").val());
	$("#step3 span#accName_answer").html($("#q56550_q4").val());
	$("#step3 span#accNumber_answer").html($("#q56550_q5").val());
	$("#step3 span#sortCode_answer").html($("#q56550_q6").val());

	if ($("#q50396_q37").val() == "Other") {
		$("#step3 span#title_answer").html($("#q50396_q44").val());
	} else {
		$("#step3 span#title_answer").html($("#q50396_q37").val());
	}
	
	$("#step3 span#firstName_answer").html($("#q50396_q5").val());
	$("#step3 span#lastName_answer").html($("#q50396_q6").val());
	$("#step3 span#dob_answer").html($("#q50396\\:q52value\\[d\\]").val() + " / " + $("#q50396\\:q52value\\[m\\]").val() + " / " + $("#q50396\\:q52value\\[y\\]").val());
	$("#step3 span#add1_answer").html($("#q50396_q7").val());
	
	if ($("#q50396_q39").val() == "") {
		$("#step3 span#add2_answer").html($("#q50396_q39").val());
	} else {
		$("#step3 span#add2_answer").html("&nbsp;");
	}

	if ($("#q50396_q40").val() == "") {
		$("#step3 span#add3_answer").html($("#q50396_q40").val());
	} else {
		$("#step3 span#add2_answer").html("&nbsp;");
	}

	$("#step3 span#towncity_answer").html($("#q50396_q8").val());
	$("#step3 span#county_answer").html($("#q50396_q9").val());
	$("#step3 span#postcode_answer").html($("#q50396_q11").val());
	$("#step3 span#phone_answer").html($("#q50396_q12").val());
	$("#step3 span#mobile_answer").html($("#q50396_q14").val());
	$("#step3 span#email_answer").html($("#q50396_q35").val());

	$("#step3").show();
	$("#customForm").scrollTo(500);
} // end displayConfirmation

// Step 1 check
function checkForm() {
	inlineFormValidate.checkField("q56550_q12", "^[1-9]\\d{0,10}.?\\d{0,2}$", "Please enter a valid amount", 1);
	if (!bankvalid) {
		$("#q56550_q5, #q56550_q6").parent().removeClass("requiredOkay").addClass("requiredError");
		$("#formErrors").html("Please check your bank details");
		$("#customForm").scrollTo(500);
	} else if ($("#customForm div").hasClass("requiredError")) {
		$("#formErrors").html(errorMessage);
		$("#customForm").scrollTo(500);
	} else {
		$("#formErrors").html("");
		$("#content").scrollTo(500);
		$("#step1").hide();
		$("#step2").show();
		$("#step2Buttons").show();
	}
} // end checkForm

function updateGiftAidAmt(donationAmount){
	var basicTax = 20; 

	// check amount
	if (donationAmount == 0 || isNaN(donationAmount)) {
		donationAmount = 10;
	}

	giftAidAmt = new Number(donationAmount * (basicTax / (100 - basicTax)) * 12);

	// update the values on page
	document.getElementById('amtExtraGiftAid').innerHTML = giftAidAmt.toFixed(2);
	document.getElementById('donAmt').innerHTML = donationAmount;
	document.getElementById('donAmt2').innerHTML = donationAmount;
	document.getElementById('taxAmt').innerHTML = giftAidAmt.toFixed(2);

} // updateGiftAidAmt

function doInlineCheck(fieldname, prefix) {
	switch (fieldname) {
		// section 1
		case "q56550_q12": // donation amount
			inlineFormValidate.checkField(fieldname, inlineFormValidate.amountRegExp, "Please enter a valid amount", 1);
			updateGiftAidAmt();
			break;
		case "q56550_q18":
			if ($("#q56550_q14_1").attr("checked")) {
				inlineFormValidate.checkField(fieldname, "^\\d{1,20}$", "Please enter your reference number.", 1);
			}
			break;
		case "q56550_q4": // acc name
			inlineFormValidate.checkField(fieldname, inlineFormValidate.textBoxRegExp, "Please enter your account name", 1);
			break;
		case "q56550_q5": // acc number
			inlineFormValidate.checkField(fieldname, "^\\d{8}$", "Your account number should be 8 digits", 1);
			break;
		case "q56550_q6": // sort code
			inlineFormValidate.checkField(fieldname, "^\\d{6}$", "Your sort code should be 6 digits", 1);
			break;
		// section 2
		case "q50396_q37": // title
			inlineFormValidate.checkTitle("q50396_q37", "q50396_q44");
			break;
		case "q50396_q44":// other title 
			if (!$("#q50396_q44").attr("disabled")) {
				inlineFormValidate.checkField(fieldname, "^.{1,100}$", "Please enter a title", 1);
			}
			break;
		case "q50396_q5": // first name
			inlineFormValidate.checkField(fieldname, inlineFormValidate.textBoxRegExp, "Please fill in your first name", 1);
			break;
		case "q50396_q6": // surname
			inlineFormValidate.checkField(fieldname, inlineFormValidate.textBoxRegExp, "Please fill in your surname", 1);
			break;
		case "q50396_q7": // address 1
			inlineFormValidate.checkField(fieldname, inlineFormValidate.textBoxRegExp, "Please enter your address", 1);
			break;
		case "q50396_q39": // address 2
		case "q50396_q40": // address 3
		case "q50396_q9": // county
			inlineFormValidate.checkField(fieldname, inlineFormValidate.textBoxRegExp, "", 0);
			break;
		case "q50396_q8": // Town/city
			inlineFormValidate.checkField(fieldname, inlineFormValidate.textBoxRegExp, "Please enter your town/city", 1);
			break;
		case "q50396_q11": // simple postcode validation
			inlineFormValidate.checkField(fieldname, inlineFormValidate.postcodeRegExp, "Please enter a valid postcode", 1);
			break;
		case "q50396_q35": // email address
			inlineFormValidate.checkField(fieldname, inlineFormValidate.emailRegExp, "Please enter a valid email address", 1);
			break;
		case "q50396_q43": // confirm email address 
			inlineFormValidate.checkField(fieldname, inlineFormValidate.emailRegExp, "Please enter a valid email address", 1);
			inlineFormValidate.checkEmailConfirm("q50396_q35", fieldname);
			break;
		case "q50396_q12": // phone number
			inlineFormValidate.checkField(fieldname, inlineFormValidate.phoneRegExp, "Please enter a valid phone number without spaces", 0);
			break;
		case "q50396_q14": // mobile phone number
			inlineFormValidate.checkField(fieldname, inlineFormValidate.phoneRegExp, "Please enter a valid mobile phone number without spaces", 0);
			break;
	}
} // end doInlineCheck

function initForm() {
	var addresslines = ["q50396_q7","q50396_q39", "q50396_q40", "q50396_q8", "q50396_q9", "q50396_q11"];
	var formID = "form_email_50396";

	// set appeal code
	$('#q50396_q16').val(getQueryVariable('appeal', ''));

	// set landing page choice
	$('#q50396_q50').val(getQueryVariable('lp', ''))

	// section hides
	$("#step2").hide();
	$("#step1Buttons").show();
	$("#step3Buttons").hide();

	// set focus on the donation amount
	$("#q56550_q12").focus();

	// manually enter address
	$("#addressLookup").show();
	$("#enterAddress").click(function() {
		$("#enterAddressLink").hide();
		$("#addressLookup").slideUp(500);
		$("#addressFields").slideDown(500);
		return false;
	});

	// update gift aid amount
	updateGiftAidAmt($("#q56550_q12").val());
	$("#q56550_q12").bind("change", function(e) {
		updateGiftAidAmt(this.value);
	});

	// Reference box
	$("#existingReference").hide();
	$("#q56550_q14_1").click(function() {
		$("#existingReference").show();
	});

	// toggle the reference number box
	$("#q56550_q14_0").click(function() {
		$("#existingReference").hide();
		$("#q56550_q18").val("");
		$("#q56550_q18").parent().removeClass("requiredError");
		$("#q56550_q18_reqMsg").remove();
	});

	// generic all form elements bind
	$("#" + formID + " :input").blur(function() {
		doInlineCheck($(this).attr("id"));
	});

	// check for current focused item and always do a DOB check if not a select drop down
	$("#customForm input").focus(function() {
		currentFocus = $(this).attr("id");
		inlineFormValidate.checkDOB("#q50396\\:q52value\\[d\\]", "#q50396\\:q52value\\[m\\]", "#q50396\\:q52value\\[y\\]", true, false);
	})
	
	$("#q50396_q44").attr("disabled", "disabled"); // disable the other title box

	// display the address lookup
	$("#addressLookup").show();
	$("#addressFields").hide();
	addressLookUp.addressLines = addresslines;
	addressLookUp.updateAddressLabels();

	// Gift Aid qualify link
	$("#qualifyText").hide();
	$("#qualifyLink").click(function() {
		$("#qualifyText").show();
		return false;
	});

	// gift aid calculator
	$("#q56550_q12").bind("change", function() {
		updateGiftAidAmt($("#q56550_q12").val());
	});
	updateGiftAidAmt($("#q56550_q12").val());

	// Binds postcode lookup 
	$("#lookupsubmit").bind("click", $("#lookup_postcode"), function (e) {
		addressLookUp.clearAddressErrors();
		addressLookUp.lookUp(e, "#lookup_house_no", "#lookup_postcode");
	});

	// setup step 1 submit
	$("#step1_submit").bind("click", function(e) {
		var accNumber = $("#q56550_q5").val();
		var sortCode = $("#q56550_q6").val();

		$("#step1 :input").each(function() {
			doInlineCheck($(this).attr("id"));
		});

		if ($("#customForm div").hasClass("requiredError")) {
			$("#formErrors").html("<div style=\"color:#f00;\"><strong>Please correct the information in the fields below.</strong></div>");
			$("#customForm").scrollTo(500);
		} else {
			checkBankDetails(accNumber, sortCode);
		}
	});

	// setup step 2 submit
	$("#step2_submit").bind("click", function(e) {
		$("#addressFields").show();
		// checkFormStep2();
		$("#step2 :input").each(function() {
			doInlineCheck($(this).attr("id"));
		});

		if ($("#customForm div").hasClass("requiredError")) {
			$("#formErrors").html(errorMessage);
			$("#customForm").scrollTo(500);
		} else {
			$("#formErrors").html("");
			$("#customForm").scrollTo(500);
			displayConfirmation();
			$("#step3Buttons").show();
		}
	});

	// Form submit
	$("#step3_submit").bind("click", function(e) {
		$("#form_email_50396").submit();
	});

} // end initForm

// jquery reliant actions
$(document).ready (function(){
	initForm();

	// for switching back to edit mode
	$("#editDetails").bind("click", function(e) {
		$("#step3Buttons").hide();
		$("#step3").hide();
		$("#resourcebox-bottom").hide();
		$("#step1").show();
	});
}); // end of jQuery functions

