
addEvent(window, 'load', initValidate);			// loads form validation

//-----------------------------------------------------------------------------

function initValidate()
{
	if (document.forms)
		{
		var inputs = []
		var uniques = []
		var qsArray = []

		inputs = getObject('input', 'tag')

		uniques = filter(inputs, 'unique', uniques, 'tag')

		if (uniques.length > 0)
			{
			screenReaderMessage()		// sets up alerts toggle for screen readers
			}

		var qs = window.location.search	// check querystring
		qsArray = qs.split("&")

		for (var i=(qsArray.length-1); i>=0;i--)
			{
			if (qsArray[i].search("pin") != '-1')
				{
				fetchPINdetails(qsArray[i].slice(5,9), qsArray[i].slice(9));
				break;
				}
			}

		var allforms = document.forms
		doctitle = document.title

		for (var i=(allforms.length-1); i>=0; i--)
			{
			if (/\bsomerequired\b/.exec(allforms[i].className))	// Identify required forms by class
				{
				var thisForm = allforms[i]
				var elems = thisForm.elements
				thisForm.submits = []
				thisForm.reqElems = []
				thisForm.filled = 0
				thisForm.required = 0

				for (var k=(elems.length-1); k>=0; k--)
					{
					if (elems[k].type == 'submit')				// finding submit buttons, and build array in case of multiples
						{
						thisForm.submits[thisForm.submits.length] = elems[k]
						elems[k].origTitle = ''
						elems[k].origValue = elems[k].value
						}

					if (/\bunique\b/.exec(elems[k].className))		// a form field that needs to be checked for uniqueness
						{
						elems[k].parentForm = thisForm
						elems[k].onblur = checkUnique
						}

					if (elems[k].id == 'pin')				// pin; used to fetch org details etc on Selfreg.asp
						{
						elems[k].parentForm = thisForm
						elems[k].onblur = formPIN
						}

					if (elems[k].id == 'newpassword')		// password field; checked for length
						{
						elems[k].parentForm = thisForm
						elems[k].onblur = checkPassword
						}

					if (elems[k].id == 'newconfpassword')	// confirm password field; checked that it matches above
						{
						elems[k].parentForm = thisForm
						elems[k].onblur = checkConfirmPassword
						}

					if (/\bemail\b/.exec(elems[k].className))		// email field; checked for validity
						{
						elems[k].parentForm = thisForm
						elems[k].onblur = checkEmail
						}

					if (/\brequired\b/.exec(elems[k].className))	// all required form fields
						{
						thisForm.reqElems[thisForm.reqElems.length] = elems[k]
						elems[k].parentForm = thisForm
						elems[k].onchange = checkValue
						thisForm.required++
						}
					}

				for (var f=(thisForm.reqElems.length-1); f>=0; f--)	// initially disable submit buttons if fields are loaded empty
					{
					var currentElem = thisForm.reqElems[f]

					if (currentElem.value != "")
						{
						thisForm.filled++
						}
					}

				if (thisForm.filled != thisForm.required)
					{
					disableSubmit(thisForm.reqElems[0])
					}

				}
			}
		}
}

//----------------------------------------------------------------------------------- selfreg PIN functions

function formPIN()
{
	fetchPINdetails(this.value.slice(0,4), this.value.slice(4))
}

function fetchPINdetails(initials, pin)
{
	var request = createXMLHttpRequest()

	request.open("GET", "/helresources/includes/ni_handlers/ni_fetch_PINdetails.asp?initials=" + initials + "&pin=" + pin, true)

	request.onreadystatechange = function()
		{
		if (request.readyState != 4) {return;}
		if (request.responseText.slice(0,5) == "Sorry")
			{
			var problem = request.responseText
			deleteDetails()
			buildMessage(document.forms.selfreg, problem);
			addPINfield();
			}
		else
			{writePINdetails(request.responseText)}
		}
	request.send(null)
}

function addPINfield()		// writes in form field for PIN when querystring PIN is invalid or empty (not for invalid form field PIN)
{
	var oldPIN = document.forms.selfreg.elements.pin
	if(oldPIN.type == 'hidden')						// removing hidden pin formfield with wrong value, writing in new form field PIN
		{
		var PINlabel = document.createElement('label')
		PINlabel.htmlFor = 'pin'
		PINlabel.innerHTML = 'PIN:'

		var PINfield = document.createElement('input')
		PINfield.type = 'text'
		PINfield.className = 'text short required'
		PINfield.name = 'pin'
		PINfield.id = 'pin'

		PINlabel.appendChild(PINfield)

		insertAfter(oldPIN.parentNode, PINlabel, oldPIN)

		oldPIN.parentNode.removeChild(oldPIN)
		}
}

function writePINdetails(details)
{
	var GrpNames = details.split("*")[0]
	GrpNames = GrpNames.substring(0, GrpNames.length-1)
	var GrpsArray = GrpNames.split(",")

	var CourseNames = details.split("*")[1]
	if (CourseNames)
		{
		if (CourseNames.slice(0,5) == "Sorry")
			{var noCourses = "yes"}

		else
			{
			CourseNames = CourseNames.substring(0, CourseNames.length-1)
			var coursesArray = CourseNames.split(",")
			coursesStr = ''

			for (var k=0; k<coursesArray.length; k++)
				{
				var coursesStr = coursesStr + coursesArray[k]
				if (k != coursesArray.length-1)
					{coursesStr = coursesStr + ', '}
				}
			}
		}

	deleteDetails()
	deleteMessage()

	var dets = document.createElement('p')
	dets.id = "details"
	dets.className = "confirm"
	dets.title = "confirm"
	dets.innerHTML = ("The PIN number you've given is for <strong>" + GrpsArray[1] + "</strong>.")

	var infoPara = document.getElementById('info')
	insertAfter(infoPara.parentNode, dets, infoPara)

	if (noCourses == "yes")
		{
		var warning = document.createElement('p')
		warning.className = "warning"
		warning.title = "warning"
		warning.innerHTML = CourseNames

		insertAfter(dets.parentNode, warning, dets)
		}

	else
		{dets.innerHTML = dets.innerHTML + (" It will give you access to the following course groups - <strong>" + coursesStr + "</strong>. If this is correct, you'll need to fill in the form below and press submit. If not, please contact your administrator.")}
}

function deletedets()
{
	if(document.getElementById('details'))
		{
		var oldDets = document.getElementById('details')
		oldDets.parentNode.removeChild(oldDets)
		}
}

//-------------------------------------------------------------------------------------

function disableSubmit(errorField)
{
	for (var t=(errorField.parentForm.submits.length-1); t>=0; t--)
		{
		var thisSubmit = errorField.parentForm.submits[t]
		thisSubmit.disabled = 'disabled'
		if (/\bdisabled\b/.exec(thisSubmit.className) == null)
			{
			thisSubmit.className = thisSubmit.className + ' disabled'
			thisSubmit.value = 'form incomplete?'
			}
		if (!(/\bdisabled\b/.exec(thisSubmit.title)))
			{thisSubmit.title += ' disabled, because one or more required fields haven\'t been completed'}
		}
}

function checkUnique()
{
	if(this.value != "")
		{
		var checkField = this
		var nameInput = this.name
		var valueInput = this.value.toLowerCase()

		var request = createXMLHttpRequest()

		request.open("GET", "/helresources/includes/ni_handlers/ni_check_unique.asp?"+ nameInput + "=" + valueInput, true)

		request.onreadystatechange = function()
			{
			if (request.readyState != 4) {return;}
			if (request.responseText != "fine")
				{
				var problem = request.responseText
				disableSubmit(checkField)
				buildMessage(problem, checkField)
				}
			else
				{deleteMessage()}
			}
		request.send(null)
		}
}

function checkPassword()	// checks entered password for length
{
	if (this.value.length <5)
		{
		buildMessage('Sorry - your Password must have at least five characters. Please try again.', this)
		}
	else
		{deleteMessage()}
}

function checkEmail()	// checks entered email address against regexp. NB doesn't disable submit; it allows a blank email
{
	if (this.value != "" && !/^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/.test(this.value))
		{
		buildMessage('Sorry - that email address isn\'t valid. Please type your address again.', this)
		}
	else
		{deleteMessage()}
}

function checkConfirmPassword()	// checks confirm password matches password field
{
	var pwdfield = document.getElementById('newpassword')

	if (this.value != pwdfield.value)
		{
		buildMessage('Sorry - the Confirm Password field must match the Password field. Please try again.', this)
		}
	else
		{deleteMessage()}
}

function checkValue()	// when a required field changes, checks to see if *any* required field is empty.
{
	this.parentForm.filled = 0

	for (var f=(this.parentForm.reqElems.length-1); f>=0; f--)
		{
		var currentElem = this.parentForm.reqElems[f]

		if (currentElem.value != "")
				{
				this.parentForm.filled++
				}
		}

	if (this.parentForm.filled == this.parentForm.required)
		{
		for (var t=(this.parentForm.submits.length-1); t>=0; t--)
			{
			var thisSubmit = this.parentForm.submits[t]
			thisSubmit.disabled = ''
			if (/\bdisabled\b/.exec(thisSubmit.className))
				{
				thisSubmit.className = thisSubmit.className.replace(/ disabled/g, "")
				thisSubmit.title = thisSubmit.origTitle + ' enabled'
				thisSubmit.value = thisSubmit.origValue
				}
			}
		}
	else
		{
		disableSubmit(this)
		}
}

function screenReaderMessage()		// gives screen-reader users a tickbox to enable alert boxes for AJAX content changes. Requires a id="maincontent"
{
	var maincont = getObject('maincontent', 'id')

	var sr_form = document.createElement('form')
	sr_form.className = 'screenRead'
	sr_form.action = '#'
	sr_form.method = 'post'
	sr_form.id = 'sr_switch'

	var sr_label = document.createElement('label')
	sr_label.htmlFor = 'sr_mess'

	var sr_check = document.createElement('input')
	sr_check.type = 'checkbox'
	sr_check.id = 'sr_mess'
	sr_check.name = 'sr_mess'

	var sr_note = document.createTextNode('This page contains dynamic content, which a screen reader may find difficult to detect. Tick this box if you want the page to alert you when content changes.')

	sr_label.appendChild(sr_note)
	sr_label.appendChild(sr_check)
	sr_form.appendChild(sr_label)

	maincont.insertBefore(sr_form, maincont.firstChild)	// glues in form before maincontent first child
}

function buildMessage(problem, problemfld)
{
	deleteMessage()

	var message = document.createElement('p')
	message.id = 'problem'
	message.title = 'problem with form field'

	var text = document.createTextNode(problem)
	message.appendChild(text)

	insertAfter(problemfld.parentNode.parentNode, message, problemfld.parentNode)

	document.title = problem + ' - ' + doctitle

	if (getObject('sr_mess', 'id'))
		{
		if (getObject('sr_mess', 'id').checked == true)
			{
			alert(problem)
			}
		}
}

function deleteMessage()
{
	if (getObject('problem', 'id'))
		{
		var oldMessage = getObject('problem', 'id')
		oldMessage.parentNode.removeChild(oldMessage)
		}
	document.title = doctitle
}