Event.observe(window, "load", init);

var globals = {}

function init() {
	// attach useful methods to elements
	Element.addMethods(elementMethods)

	// set up globals (including accordion)
	Object.extend(globals, {
		main		: $("vertical_nested_container"),
		toggles		: $$("#vertical_nested_container .vertical_accordion_toggle"),
		containers	: $$("#vertical_nested_container .vertical_accordion_content"),

		// new accordion should be new Accordion mr stickman
		nestedVerticalAccordion: new accordion("vertical_nested_container", {
			classNames: {
				toggle			: "vertical_accordion_toggle",
				toggleActive	: "vertical_accordion_toggle_active",
				content			: "vertical_accordion_content"		
			}
		}),
		error		: null
	})


	// EVENTS
	// -------------------------------------------------------------------------------------
	$("DOB","INSdate").invoke("observe", "focus", function () {
		if (this.value == "dd/mm/yyyy") this.clear()
	})
	$("DOB","INSdate").invoke("observe", "blur", function () {
		if (!$F(this)) {
			this.value = "dd/mm/yyyy"
		}
	})

	$("isSE").observe("click", function () {
		if (this.checked) {
			$("EmpCompanyName").hide()
			$("EmpCompanyNameLabel").hide()
			$("EmpCompanyName").value = "SELF EMPLOYED"
		} else {
			$("EmpCompanyName").show()
			$("EmpCompanyNameLabel").show()
			$("EmpCompanyName").clear().focus()
		}
	})

	$("PrevEmpIsSE").observe("click", function () {
		if (this.checked) {
			$("PrevEmpCompanyName").hide()
			$("PrevEmpCompanyNameLabel").hide()
			$("PrevEmpCompanyName").value = "SELF EMPLOYED"
		} else {
			$("PrevEmpCompanyName").show()
			$("PrevEmpCompanyNameLabel").show()
			$("PrevEmpCompanyName").clear().focus()
		}
	})

	$("applytoday").observe("submit", function (evt) {
		if (validate(evt)) {
			// this submission attempt is successful
			if ($F("Mobile").length == 0 && confirm("Are you sure you wish to submit this application without a mobile number? Supplying a valid UK mobile number may improve the rate we are able to provide.\n\nPress OK to enter a mobile number or Cancel to continue without one")) {
				if (!globals.toggles[1].hasClassName("vertical_accordion_toggle_active")) {
					globals.nestedVerticalAccordion.activate(globals.toggles[1])
				}
				$("Mobile").flashBorder()
				res = false
				evt.stop()
			} else {	// submit is happening now!
			
				$("submit").disabled = true
							
				$("EmpCompanyName").disabled = false
				$("PrevEmpCompanyName").disabled = false			

				var checkfields = [
					"EmployedYears","EmployedMonths","PrevEmpEmployedYears","PrevEmpEmployedMonths",
					"TimeAtAddressY","TimeAtAddressM","PrevTimeAtAddressY","PrevTimeAtAddressM"
				]
				checkfields.each(function (el) {
					if ($F(el).length == 0 || isNaN($F(el))) $(el).value = 0
				})

				return true
			}
		}	
	})

	$$("button.continue").invoke("observe", "click", function (evt) {
		if (this.hasClassName("cleared")) {
			globals.nestedVerticalAccordion.activate(
				$$(".vertical_accordion_content").find(function (el) {
					return el == evt.element().up()
				}).next()
			)
			evt.stop(); return false
		} else {
			// we need to raise the validation error here but this is shit
			
			var target = globals.error.up(".vertical_accordion_content").previous()
			if (!target.hasClassName("vertical_accordion_toggle_active")) {
				globals.nestedVerticalAccordion.activate(target)
			}
			
			// raise it
			if (globals.error) globals.error.validate.curry(false,1).bind(globals.error)()		

			evt.stop(); return false
		}
	})

	// -------------------------------------------------------------------------------------

	
	// VALIDATION FUNCTIONS (for inline and submit)
	// -------------------------------------------------------------------------------------
	// we attach these functions onto the element directly
	// so we can check if they validate in any situation

	var validateNumeric = function (silent,sub) {
		if (isNaN($F(this))) {
			if (!silent) {
				showAlert("Please fill this field with a number only",this)
				this.flashBorder().select()
			}
			return false
		}
		return true
	}

	var validateMMYY = function (silent,sub) {
		if (isNaN($F(this))) {
			if (!silent) {
				showAlert("Please fill this field with a number only",this)
				this.flashBorder().select()
			}
			return false
		}
				
		if (!$F(this).length) {
			if (sub) {
				showAlert("Please indicate the length of employment",this)
				this.flashBorder().select()
			}
			return false
		}
			
		// check to see whether we need to ask for previous address
		if (this.id == "EmployedYears" || this.id == "EmployedMonths") {
			var m = ($F("EmployedYears")) ? parseInt($F("EmployedYears")) * 12 : 0
			m += ($F("EmployedMonths")) ? parseInt($F("EmployedMonths")) : 0
			// less than 3 yrs
			if (m < 36) {
				$("previousemployer").select("INPUT","TEXTAREA","SELECT").each(function (el) { el.disabled = false })
				$("previousemployer").style.display = "block"			
			} else {
				$("previousemployer").select("INPUT","TEXTAREA","SELECT").each(function (el) { el.disabled = true })
				$("previousemployer").style.display = "none"
			}
		}

		if (this.id == "TimeAtAddressY" || this.id == "TimeAtAddressM") {
			var m = ($F("TimeAtAddressY")) ? parseInt($F("TimeAtAddressY")) * 12 : 0
			m += ($F("TimeAtAddressM")) ? parseInt($F("TimeAtAddressM")) : 0
			// less than 3 yrs
			if (m < 36) {
				$("previousaddress").select("INPUT","TEXTAREA","SELECT").each(function (el) { el.disabled = false })
				$("previousaddress").style.display = "block"
			} else {
				$("previousaddress").style.display = "none"	
				$("previousaddress").select("INPUT","TEXTAREA","SELECT").each(function (el) { el.disabled = true })
			}
		}
		
		return true
	}

	var validateFilled = function (friendlyName,silent,sub) {
		if ($F(this).length < 1) {
			if (sub) {
				showAlert("You must fill in your " + friendlyName + " to continue",this)
				this.flashBorder().select()
			}
		} else return true
	}

	var validatePostcode = function (silent) {
		if ($F(this).length && !this.isUKPostcode()) {
			if (!silent) {
				showAlert("Please enter a valid UK postcode",this)
				this.flashBorder().select()
			}
			return false
		} else return true
	}
	
	
	globals.containers[0].select("INPUT").each(function(input) {	// 6 reqs
		input.validate = function (silent,sub) {
			// we only run this next line if this is a submission attempt
			if (sub) {
				showAlert("All 6 requirements must be checked",this)
				this.up("fieldset").flashBorder()
			}
			return (input.checked) ? true : false
		}
	})

	$("Title").validate = validateFilled.curry("title")
	$("FName").validate = validateFilled.curry("first name")
	$("LName").validate = validateFilled.curry("surname")

	$("LName").validate = function (silent,sub) {
		if ($F(this).length < 2) {
			if (sub) {
				showAlert("You must fill in your surname to continue",this)
				this.flashBorder().select()
			}
		} else return true
	}
	
	$("DOB").validate = function (silent) {
		if (!this.isDate()) {
			if (!silent) {
				showAlert("Please enter a valid date in the dd/mm/yyyy format\n\ne.g. for the 31st July 1981, enter 31/07/1981",this)
				this.flashBorder().select()
				if (!globals.noFocus) this.select()
			}
			return false
		} else return true
	}

	$("Email").validate = function (silent) {
		if (!this.isEmail()) {
			if (!silent) {
				showAlert("Please enter a valid email address",this)
				this.flashBorder().select()
			}
			return false
		} else return true
	}

	$("Tel").validate = function (silent) {
		this.value = this.value.replace(" ","","g")
		if (!this.isUKPhone()) {
			if (!silent) {
				showAlert("Please enter a valid UK telephone number",this)
				this.flashBorder().select()
			}
			return false
		} else return true
	}

	$("Mobile").validate = function (silent) {
		this.value = this.value.replace(" ","","g")
		if ($F(this).length == 0) return true
		if (!this.isUKMobile()) {
			if (!silent) {
				showAlert("Please enter a valid UK mobile number, or leave blank if you do not have one",this)
				this.flashBorder().select()
			}
			return false
		} else return true
	}

	$("EmpCompanyName").validate = validateFilled.curry("company name")
	$("EmpJobTitle").validate = validateFilled.curry("job title")

	$("EmpPostcode").validate = validatePostcode
	
	$("EmpTel").validate = function (silent) {
		if (!this.isUKPhone()) {
			if (!silent) {
				showAlert("Please enter a valid UK telephone number",this)
				this.flashBorder().select()
			}
			return false
		} else return true
	}

	$("EmployedMonths").validate = validateNumeric
	$("EmployedYears").validate = validateMMYY

	$("Status").validate = validateFilled.curry("property status")
	$("Address1").validate = validateFilled.curry("address")
	$("Town").validate = validateFilled.curry("town")
	$("Postcode").validate = function (silent,sub) {
		if (!$F(this).length) {
			if (!silent) {
				showAlert("Please enter your home postcode to continue",this)
				this.flashBorder().select()
			}
		} else {
			return validatePostcode.curry(silent,sub).bind(this)()
		}
	}
	$("TimeAtAddressM").validate = validateNumeric
	$("TimeAtAddressY").validate = validateMMYY
	
	$("LoanAmount").validate = function (silent) {
		var v = $F(this)
		if (v.length > 0) {
			if (isNaN(v)) {
				if (!silent) {
					showAlert("Please fill this field with a number only",this)
					this.flashBorder().select()
				}
				return false
			} else {
				if (v < 2500) {
					if (!silent) {
						showAlert("Sorry the minimum advance we can provide is &pound;2,500",this)
						this.flashBorder().select()
					}
					return false
				}
			}
		} else {
			if (!silent) {
				showAlert("Please enter an estimate of the amount you wish to borrow",this)
				this.flashBorder().select()
			}
			return false
		}
		return true
	}

	$("MainNetIncome").validate = function (silent) {
		if ($F(this).length == 0 || isNaN($F(this))) {
			if (!silent) {
				showAlert("Please fill this field with a number",this)
				this.flashBorder().select()
			}
			return false
		} else {
			if ($F(this) < 750) {
				if (!silent) {
					showAlert("Sorry, we cannot help unless you are earning over &pound;750 p/month",this)
					this.flashBorder().select()
				}
				return false
			}
		}
		return true
	}

	$("PrevEmpCompanyName").validate = function (silent,sub) {
		if (this.up("div").visible()) {
			return validateFilled.curry("previous company name",silent,sub).bind(this)()
		} else return true
	}

	
	$("PrevEmpJobTitle").validate = function (silent,sub) {
		if (this.up("div").visible()) {
			return validateFilled.curry("previous job title",silent,sub).bind(this)()
		} else return true
	}

	$("PrevEmpPostcode").validate = function (silent,sub) {
		if (this.up("div").visible()) {
			return validatePostcode.curry(silent,sub).bind(this)()
		} else return true
	}

	$("PrevEmpTel").validate = function (silent) {
		if (this.up("div").visible()) {
			if ($F(this).length && !this.isUKPhone()) {
				if (!silent) {
					showAlert("Please enter a valid UK telephone number",this)
					this.flashBorder().select()
				}
				return false
			}
		}
		return true
	}	
	
	$("PrevEmpEmployedMonths").validate = validateNumeric

	$("PrevEmpEmployedYears").validate = function (silent,sub) {
		if (this.up("div").visible()) {
			return validateMMYY.curry(silent,sub).bind(this)()
		} else return true
	}


	$("PrevStatus").validate = function (silent,sub) {
		if (this.up("div").visible()) {
			return validateFilled.curry("previous property status",silent,sub).bind(this)()
		} else return true
	}
	$("PrevAddress1").validate = function (silent,sub) {
		if (this.up("div").visible()) {
			return validateFilled.curry("previous address",silent,sub).bind(this)()
		} else return true
	}
	$("PrevTown").validate = function (silent,sub) {
		if (this.up("div").visible()) {
			return validateFilled.curry("previous address town",silent,sub).bind(this)()
		} else return true
	}
	$("PrevPostcode").validate = function (silent,sub) {
		if (this.up("div").visible()) {
			if (!$F(this).length) {
				if (!silent) {
					showAlert("Please provide your previous address postcode to continue",this)
					this.flashBorder().select()
				}
				return false
			} else return validatePostcode.curry(silent,sub).bind(this)()
		}
		return true
	}

	$("PrevTimeAtAddressM").validate = validateNumeric
	
	$("PrevTimeAtAddressY").validate = function (silent,sub) {
		if (this.up("div").visible()) {
			return validateMMYY.curry(silent,sub).bind(this)()
		} else return true
	}

	document.getElementsByName("CarInsurance")[0].validate = function (silent,sub) {
		var a = $A(document.getElementsByName("CarInsurance"))
		if (!a.find(function (el) { return el.checked })) {
			if (sub) {
				showAlert("Would you like us to assist you with finding the cheapest available motor insurance?",a[0])
				a.invoke("flashBorder")
			}
			return false
		}
		return true
	}

	$("INSvehiclemake").validate = function (silent,sub) {
		if (document.getElementsByName("CarInsurance")[0].checked) {
			return validateFilled.curry("vehicle make",silent,sub).bind(this)()
		} else return true
	}

	$("INSvehiclemodel").validate = function (silent,sub) {
		if (document.getElementsByName("CarInsurance")[0].checked) {
			return validateFilled.curry("vehicle model",silent,sub).bind(this)()
		} else return true
	}

	$("INScover").validate = function (silent,sub) {
		if (document.getElementsByName("CarInsurance")[0].checked) {
			return validateFilled.curry("cover type",silent,sub).bind(this)()
		} else return true
	}
	
	$("INSdate").validate = function (silent) {
		if (document.getElementsByName("CarInsurance")[0].checked && !this.isDate()) {
			if (!silent) {
				showAlert("Please enter a valid date in the dd/mm/yyyy format\n\ne.g. for the 31st July 1981, enter 31/07/1981",this)
				this.flashBorder().select()
			}
			return false
		} else return true
	}


	// -------------------------------------------------------------------------------------


	// register global validation handler
	globals.main.select("INPUT","TEXTAREA","SELECT").invoke("observe", "change", validate)

	// validate apply form now incase it has persisted from a previous load
	validate()

	// open first accordion
	globals.nestedVerticalAccordion.activate(globals.toggles[0]);
}

// global validation handler - used for submissions and inline
function validate(evt) {
	if (evt) {		// has occured from an event/user action (onchange, onblur etc..)
		el = evt.element()
		
		// run validation immediately for current validation
		// this gives user alerts etc..
		if (el.validate) el.validate(false)
	}
	
	// get a copy of the containers array to use as validation checklist
	var containers = globals.containers.clone()

	// to store first input error (we'll use this later if this is a bad submission attempt)
	var firstError
	
	// validate the whole form
	globals.containers.each(function (container,i) {
		// validate container
		var inputs = container.select("INPUT","SELECT","TEXTAREA")
		
		inputs.each(function (input,i) {
			// validate input
			if (input.validate) {
				// run validation function with silent flag
				inputs[i] = input.validate(true)
				// store this field as our first error incase this is a submit request
				if (!inputs[i] && !firstError) firstError = input
			} else inputs[i] = true		// no validation reqd
		})

		// for the continue button
		var button = containers[i].select("button.continue")[0]

		if (inputs.all()) {		// all marked true
			globals.toggles[i].addClassName("cleared")
			globals.toggles[i].removeClassName("error")
			if (button) button.addClassName("cleared")
			containers[i] = true
			//$("tickcomplete").style.display ="block"
			
		} else {				// not all marked true
			globals.toggles[i].removeClassName("cleared")
			if (button) button.removeClassName("cleared")
			containers[i] = false
		}
	})

	globals.error = firstError

	// is this a submission attempt?
	if (evt && evt.type == "submit") {
		// stop if everything is not cool (ie at last one container val is false)
		if (!containers.all()) {
			// we need to raise the first validation input error here

			// find the accordion with the error field
			var containerIndex = globals.containers.indexOf(
				globals.containers.find(
					function (con) { return firstError.up(".vertical_accordion_content") == con }
				)
			)

			// show it if its hidden
			if (containerIndex) {
				if (globals.containers[containerIndex].style.display == "none") {
					globals.nestedVerticalAccordion.activate(globals.toggles[containerIndex])
				}
			}
			
			// raise the error
			if (firstError) firstError.validate(false,1)	// we pass the 1 to signal submission to some elements

			// now stop processing
			evt.stop(); return false
		}	
		// if everything is cool let it run
	}

	// if u got here u got successfully validated
	return true
}

function showAlert(msg,el) {
	if ($("alert")) {
	
		$("alert").innerHTML = msg;
		$("alert").style.display = "block"
		el.observe("click", function () {
			$("alert").style.display = "none"
			
		})
	}	

	if (el) {
		el = $(el)
		el.up('.vertical_accordion_content').previous('.vertical_accordion_toggle').addClassName("error")
	}
}
