// appTools.js

var jointActive = false;
var jointRequireds = {};


//=========================================================================================================================
// toggle joint account info

function allJointOff() {
	if ($("jointApplicant1")) {
		$("jointApplicant1").setStyle("display","none");
		$$("#jointApplicant1 input.required").removeClass("required");
	}
	if ($("jointApplicant2")) {
		$("jointApplicant2").setStyle("display","none");
		$$("#jointApplicant2 input.required").removeClass("required");
	}
}

function oneJointOff() {
	if ($("jointApplicant1")) {
		$("jointApplicant1").setStyle("display","block");
		$$("#jointApplicant1 input.jointRequired").addClass("required");
	}
	if ($("jointApplicant2")) {
		$("jointApplicant2").setStyle("display","none");
		$$("#jointApplicant2 input.required").removeClass("required");
	}	
}

function allJointOn() {
	if ($("jointApplicant1")) {
		$("jointApplicant1").setStyle("display","block");
		$$("#jointApplicant1 input.jointRequired").addClass("required");
	}
	if ($("jointApplicant2")) {
		$("jointApplicant2").setStyle("display","block");
		$$("#jointApplicant2 input.jointRequired").addClass("required");
	}	
}

function initJoint() {
	if($("jointApplicant1") && $("jointApplicant2")) {
		allJointOff();	
	}
	if ($("jointOwner0") && $("jointOwner1") && $("jointOwner2")) {
		$("jointOwner0").addEvent("click", allJointOff);
		$("jointOwner1").addEvent("click", oneJointOff);
		$("jointOwner2").addEvent("click", allJointOn);
	}
}
//=========================================================================================================================
// toggle account info for online banking app

function toggleAccountInfo() {

	if(document.getElementById('account_switch').checked == true) { 
			$('account_info').setStyle('display', 'block'); 
	} 
	else {
			$('account_info').setStyle('display', 'none');
	}
	
}

//=========================================================================================================================
// toggle beneficiary info

function allBeneficiaryOff() {
	if ($("beneficiary1")) {
		$("beneficiary1").setStyle("display","none");
		$$("#beneficiary1 input.required").removeClass("required");
	}
	if ($("beneficiary2")) {
		$("beneficiary2").setStyle("display","none");
		$$("#beneficiary2 input.required").removeClass("required");
	}
}

function oneBeneficiaryOff() {
	if ($("beneficiary1")) {
		$("beneficiary1").setStyle("display","block");
		$$("#beneficiary1 input.jointRequired").addClass("required");
	}
	if ($("beneficiary2")) {
		$("beneficiary2").setStyle("display","none");
		$$("#beneficiary2 input.required").removeClass("required");
	}	
}

function allBeneficiaryOn() {
	if ($("beneficiary1")) {
		$("beneficiary1").setStyle("display","block");
		$$("#beneficiary1 input.jointRequired").addClass("required");
	}
	if ($("beneficiary2")) {
		$("beneficiary2").setStyle("display","block");
		$$("#beneficiary2 input.jointRequired").addClass("required");
	}	
}

function initBeneficiary() {
	if($("beneficiary1") && $("beneficiary2")) {
		allBeneficiaryOff();	
	}
	if ($("beneficiarySwitch0") && $("beneficiarySwitch1") && $("beneficiarySwitch2")) {
		$("beneficiarySwitch0").addEvent("click", allBeneficiaryOff);
		$("beneficiarySwitch1").addEvent("click", oneBeneficiaryOff);
		$("beneficiarySwitch2").addEvent("click", allBeneficiaryOn);
	}
}


//=========================================================================================================================
// show and hide ssn explanation

function turnOnOff() {
	
	$('ssnExplanation').toggleClass('on');
	return false;
	
}

//=========================================================================================================================
// use residential address for mailing address

function switchAddress() {
	
	if (document.getElementById("addressSwitch").checked) {
		$('address_information-mailing_address').value = $('address_information-residential_address').value;
		$('address_information-mailing_city').value = $('address_information-residential_city').value;
		$('address_information-mailing_state').value = $('address_information-residential_state').value;
		$('address_information-mailing_zip').value = $('address_information-residential_zip').value;
	}
	
}
//=========================================================================================================================
// assign ids with same value as name to all inputs except radio

function name2ID () {
	
	var inputs = document.getElementsByTagName("input");
	for (var i=0; i<inputs.length; i++) {
		if ((inputs[i].type != "radio") && !(inputs[i].id)) {
			inputs[i].id = inputs[i].name;
		}
	}
	var selects = document.getElementsByTagName("select");
	for (var i=0; i<selects.length; i++) {
		if ((selects[i].type != "radio") && !(selects[i].id)) {
			selects[i].id = selects[i].name;
		}
	}
	
}
//=========================================================================================================================
// initialize pcredit app behaviors

function initSwitch () {
	
	var fields = ["applicant_checking","applicant_savings","applicant_cd","applicant_securities","applicant_real_estate","applicant_life_insurance","applicant_automobile","applicant_other_assets","applicant_rent_mortgage","applicant_automobile_debt","applicant_other_debt"];
	var otherFields = ["alimony_payment","co_applicant_alimony_payment","guarantor_endorser","co_applicant_guarantor_endorser","unsatisfied_judgements","co_applicant_unsatisfied_judgements","bankruptcy","co_applicant_bankruptcy","rent_mortgage_switch","co_applicant_rent_mortgage_switch"];

	fields.each(function(id, i) {
		$(fields[i]).addEvent('click', function() {									
			var target = $(fields[i]+"_info");
			if (this.checked) {
				target.setStyle('display', 'block');
			} else {
				target.setStyle('display', 'none');
			}
		});
		$("co_"+fields[i]).addEvent ('click', function() {
			var target = $("co_"+fields[i]+"_info");
			if (this.checked) {
				target.setStyle('display', 'block');
			} else {
				target.setStyle('display', 'none');
			}
		});
		var target = $(fields[i]+"_info");
		target.setStyle('display', 'none');
		var CAtarget = $("co_"+fields[i]+"_info");
		CAtarget.setStyle('display', 'none');
	});

	otherFields.each(function(id, i) {
		var radioButtons = $$('input[name='+id+']');
		radioButtons[0].addEvent('click', function() {
			var target = $(id+"_info");
			target.setStyle('display', 'none');
		});
		radioButtons[1].addEvent('click', function() {
			var target = $(id+"_info");
			target.setStyle('display', 'block');
		});
		$(id+"_info").setStyle('display', 'none');
	});
	
	document.pcredit.secured[0].onclick = function () {
		var target = document.getElementById("sectionE");
		target.style.display = 'block';
	}
	document.pcredit.secured[1].onclick = function () {
		var target = document.getElementById("sectionE");
		target.style.display = 'none';
	}
	
}
//=========================================================================================================================
// validation

var validationErrorMessage = new Object();
validationErrorMessage['required'] = 'Please answer this question to continue';
validationErrorMessage['numeric'] = 'Please answer this question with a number';
validationErrorMessage['numericStrict'] = 'Please answer this question with a number';
validationErrorMessage['pattern'] = 'Pattern incorrect';
validationErrorMessage['email'] = 'Please enter a valid email address';

var validationFunctions = new Object();
validationFunctions["required"] = isRequired;
validationFunctions["pattern"] = isPattern;
validationFunctions["numeric"] = isNumeric;
validationFunctions["numericStrict"] = isNumericStrict;
validationFunctions["email"] = isEmail;

function isRequired(formField) {
	switch (formField.type) {
		case 'text':
		case 'textarea':
		case 'select-one':
			if (formField.value && (formField.value != validationErrorMessage['required']))
				return true;
			return false;
		case 'radio':
			var radios = formField.form[formField.name];
			for (var i=0;i<radios.length;i++) {
				if (radios[i].checked) return true;
			}
			return false;
		case 'checkbox':
			return formField.checked;
	}	
}

function isPattern(formField,pattern) {
	var regExp = new RegExp("^"+pattern+"$","");
	var correct = regExp.test(formField.value);
	return correct;
}

function isNumeric(formField) {
	return isPattern(formField,"([0-9\\s\(\)\-\.\+])*");
}

function isNumericStrict(formField) {
	return isPattern(formField,"(\\d)*");
}

function isEmail(formField) {
	return isPattern(formField,"([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+")
}

function emptyFunction() {
	return true;	
}
/*
function insertOptIn() {
	if (document.getElementById("optInArea")) {
		var optInArea = document.getElementById("optInArea");
		optInArea.innerHTML = "<fieldset id='optIn'><p>Unfortunately <strong>your zip code is outside of our account-opening area</strong>, please select one of the options below:</p><input type='checkbox' name='moving' id='moving' /><label for='moving'><strong>I am moving to the area</strong>, please continue to consider my application.</label><input type='checkbox' name='opt_in' id='opt_in' /><label for='opt_in'><strong>I agree to be contacted by another bank</strong> offering a similar product and give permission to have the information contained in this application passed to that bank.</label></fieldset>";
	}
}

function zipCodeInArea() {
	if (document.getElementById("residential_zip")) {
		var zipCodePlusFour = document.getElementById("residential_zip").value;
		var zipCode = zipCodePlusFour.substr(0,5);
		var zipInArea = false;
		for(var i=0;i<zips.length;i++) {
			if (zipCode == 	zips[i]) {
				zipInArea = true;
			}
		}
		if (!zipInArea) {
			if (document.getElementById("moving") && document.getElementById("opt_in")) {
				if (document.getElementById("moving").checked || document.getElementById("opt_in").checked) {
					return true;
				}
			}
			insertOptIn();	
		}
		return zipInArea;
	} else {
		return true;
	}
}
*/
/*********************************/

function validateForms() {
	if ($$('form')[1]) {
		$$('form')[1].addEvent("submit", validate);
	} else {
		$$('form')[0].addEvent("submit", validate);
	}
}

function validate( event ) {
	if ($$('form')[1]) {
		var els = $$('form')[1].elements;
	} else {
		var els = $$('form')[0].elements;
	}
	var validForm = true;
	var firstError = null;
	for (var i=0;i<els.length;i++) {
		if (els[i].removeError)
			els[i].removeError();
		var req = els[i].className;
		if (!req) continue;
		var reqs = req.split(' ');
		for (var j=0;j<reqs.length;j++) {
			if (!validationFunctions[reqs[j]])
				validationFunctions[reqs[j]] = emptyFunction;
			var OK = validationFunctions[reqs[j]](els[i]);
			if (OK != true) {
				var errorMessage = OK || validationErrorMessage[reqs[j]];
				writeError(els[i],errorMessage)
				validForm = false;
				if (!firstError)
					firstError = els[i];
				break;
			}
		}
	}

	if (!validForm) {
		e = new Event(event).stop();
		
		alert("Sorry, there was a problem submitting your form.  Please check the highlighted fields and try again.");
		location.hash = '#';
	} else if ($('personal_information-dob_day') && $('personal_information-dob_month') && $('personal_information-dob_year')) {
		validForm = validateDate();	
	}
	/*
	if (validForm) {
		validForm = zipCodeInArea();	
	}
	*/
	return validForm;
}

function valiDate (day, month, year) {
	var now = new Date;
	var currentYear = now.getFullYear();
	if ((year < 1850) || (year > currentYear) || (month < 0) || (month > 11) || (day <= 0) || (day > 31)) {
		return false;
	}	
	switch (month) {
		case 3:
		case 5:
		case 8:
		case 10:
			if (day > 30) {
				return false;
			}
			break;
		case 1:
			if (year % 4 == 0) {
				if (day > 29) {
					return false;
				}
			} else {
				if (day > 28) {
					return false;
				}
			}
			break;
	}
	return true;
}

function validateDate () {
	var dobDay = $("personal_information-dob_day").value;	
	var dobMonth = $("personal_information-dob_month").value - 1;
	var dobYear = $("personal_information-dob_year").value;

	var now = new Date();
	var targetDay = now.getDate();
	var targetMonth = now.getMonth();
	var currentYear = now.getFullYear();
	var targetDate = Date.UTC(currentYear - 13, targetMonth, targetDay);
	
	if (!valiDate(dobDay, dobMonth, dobYear)) {
		alert("Please enter a valid date of birth");
		return false;
	}
	
	var dob = Date.UTC(dobYear, dobMonth, dobDay);
	if (dob > targetDate) {
		alert("Sorry, we cannot accept information from anyone under the age of "+13);
		return false;	
	} else if (jointActive) {
		var CoApplicantDobDay = $("joint_account-dob_day").value;	
		var CoApplicantDobMonth = $("joint_account-dob_month").value - 1;
		var CoApplicantDobYear = $("joint_account-dob_year").value;
		if (!valiDate(CoApplicantDobDay, CoApplicantDobMonth, CoApplicantDobYear)) {
			alert("Please enter a valid date of birth for Co-Applicant");
			return false;
		}
		var CoApplicantDob = Date.UTC(CoApplicantDobYear, CoApplicantDobMonth, CoApplicantDobDay);
		if (CoApplicantDob > targetDate) {
			alert("Sorry, we cannot accept information from anyone under the age of 13");
			return false;
		}
	}
	return true;
}

function writeError(obj,message) {
	obj.className += ' errorMessage';
	obj.onfocus = removeError;
	if (obj.errorMessage || obj.parentNode.errorMessage) return;
	var errorMessage = document.createElement('label');
	errorMessage.className = 'errorMessage';
	errorMessage.setAttribute('for',obj.id);
	errorMessage.setAttribute('htmlFor',obj.id);
	errorMessage.appendChild(document.createTextNode(message));
	obj.value = message;
	obj.style.backgroundColor = "#FEE";
	obj.errorMessage = errorMessage;
}

function removeError() {
	this.className = this.className.replace(/errorMessage/,'');
	if (this.errorMessage) {
		this.value = "";
		this.style.backgroundColor = "#FFF";
		this.errorMessage = null;
	}
	this.onchange = null;
}
//=========================================================================================================================
// initialize apptools

window.addEvent('domready', function() {
		jointRequireds = $$(".jointRequired");
		name2ID();
		initJoint();
		if ($("account_switch")) {
			toggleAccountInfo();
		}
		if (document.pcredit) {
			initSwitch();
		}
		initBeneficiary()
		validateForms();
});