addEvent(window, 'load', initValidate);	// form validation

//********************************

function initValidate()
{
	if (document.forms)
		{
		doctitle = document.title
		var validforms = []
		validforms = filter(document.forms, 'validated', validforms, 'tag')

		for (var i=(validforms.length-1); i>=0;i--)
			{
			var thisForm = validforms[i]
			var elems = thisForm.elements
			thisForm.submits = []
			thisForm.reqElems = []
			thisForm.filled = 0
			thisForm.required = 0

			for (var k=(elems.length-1); k>=0; k--)
				{
				elems[k].ok = 0

				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].title
					}

				if (/\brequired\b/.exec(elems[k].className))	// all required form fields
					{
					thisForm.reqElems[thisForm.reqElems.length] = elems[k]

					if (elems[k].value != "")				// required fields that are already loaded from db
						{thisForm.filled++}
					else
						{elems[k].ok = "no"}

					thisForm.required++
					elems[k].parentForm = thisForm
					elems[k].onchange = checkRequired
					}

				if (/\bunique\b/.exec(elems[k].className))		// a form field that needs to be checked for uniqueness
					{
					var sRMneeded = 'yes'
					elems[k].parentForm = thisForm
					elems[k].onblur = checkUnique
					}

				if (/\bpassword\b/.exec(elems[k].className))	// password field; checked for length
					{
					elems[k].parentForm = thisForm
					elems[k].onblur = checkPassword
					}

				if (/\bemail\b/.exec(elems[k].className))		// email field; checked for validity
					{
					elems[k].parentForm = thisForm
					elems[k].onblur = checkEmail
					}
				}

			if (thisForm.filled != thisForm.required)			// disable submit buttons and begin ongoing check for fields
				{
				disableSubmit(thisForm)
				setInterval(function(){runCheck(thisForm);}, 1000)
				}
			}

		if (sRMneeded == 'yes')
			{screenReaderMessage()}						// sets up alerts toggle for screen readers when check unique via AJAX needed
		}
}

//---------------------------------------------------------------------------------------------

function disableSubmit(form)
{
	for (var t=(form.submits.length-1); t>=0; t--)
		{
		var thisSubmit = form.submits[t]
		thisSubmit.disabled = 'disabled'
		if (/\bdisabled\b/.exec(thisSubmit.className) == null)
			{
			thisSubmit.className = thisSubmit.className + ' disabled'
			}
		if (!/\bdisabled\b/.exec(thisSubmit.title))
			{thisSubmit.title += 'Submit is disabled, because one or more fields haven\'t been completed correctly.'}
		}
}

function enableSubmit(form)
{
	for (var t=(form.submits.length-1); t>=0; t--)
		{
		var thisSubmit = form.submits[t]
		thisSubmit.disabled = ''
		if (/\bdisabled\b/.exec(thisSubmit.className))
			{
			thisSubmit.className = thisSubmit.className.replace(/ disabled/g, "")
			thisSubmit.title = thisSubmit.origTitle + 'Enabled'
			}
		}
}

//---------------------------------------------------------------------------------------------

function checkRequired()												// required fields
{
	this.parentForm.filled = 0

	for (var f=(this.parentForm.reqElems.length-1); f>=0; f--)
		{
		var currentElem = this.parentForm.reqElems[f]

		if (currentElem.value == "")
			{
			currentElem.ok = "no"
			currentElem.className = currentElem.className + " error"
			}
		else
			{
			currentElem.ok = "yes"
			currentElem.className = currentElem.className.replace(/ error/g, "")
			this.parentForm.filled++
			}
		}
}

function checkUnique()												// fields that need to be unique
{
	if(this.value != "")
		{
		var checkField = this
		var nameInput = this.name
		var valueInput = this.value.toLowerCase()

		var request = createXMLHttpRequest()

		if (location.search.indexOf('licenseID') != -1)
			{
			var licID = (location.search.substr(location.search.indexOf('licenseID')+10))
			var licenseStr = '&licenseid=' + licID
			}
		else
			{var licenseStr = ''}

		request.open("GET", "/resources/includes/utility/ni_check_unique.asp?"+ nameInput + "=" + valueInput + licenseStr, true)

		request.onreadystatechange = function()
			{
			if (request.readyState != 4) {return;}
			if (request.responseText != "fine")
				{
				checkField.ok = "no"
				checkField.className = checkField.className + " error"
				var problem = request.responseText
				buildMessage(checkField.parentForm, problem)
				}
			else
				{
				checkField.ok = "yes"
				checkField.className = checkField.className.replace(/ error/g, "")
				deleteMessage()
				}
			}
		request.send(null)
		}
}

function checkEmail()												// email field; check for validity
{
	if (this.value != "" && !/^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]+$/.test(this.value))
		{
		this.ok = "no"
		this.className = this.className + " error"
		buildMessage(this.parentForm, 'Sorry - that email address isn\'t valid. Please type the address again.')
		}
	else
		{
		this.ok = "yes"
		this.className = this.className.replace(/ error/g, "")
		deleteMessage()
		}
}

function checkPassword()											// password; check for length
{
	if (this.value.length <5)
		{
		this.ok = "no"
		this.className = this.className + " error"
		buildMessage(this.parentForm, 'Sorry - the Password must have at least five characters. Please try again.')
		}
	else
		{
		this.ok = "yes"
		this.className = this.className.replace(/ error/g, "")
		deleteMessage()
		}
}

//---------------------------------------------------------------------------------------------

function runCheck(checkform)
{
	checkform.problem = "no"

	for (var k=(checkform.elements.length-1); k>=0; k--)
		{
		if (checkform.elements[k].ok == "no")
			{
			checkform.problem ="yes"
			break;
			}
		}

	if (checkform.problem == "yes")
		{disableSubmit(checkform)}

	else
		{enableSubmit(checkform)}
}

//---------------------------------------------------------------------------------------------

function buildMessage(probForm, problem)
{
	deleteMessage()

	if (!probForm.elements[0].getElementsByTagName('legend')[0])
		{
		alert(problem)
		}
	else
		{
		var placehold = probForm.elements[0].getElementsByTagName('legend')[0]
		}
	var message = document.createElement('p')
	message.id = 'problem'
	message.className = 'problem'
	message.title = 'problem'

	var text = document.createTextNode(problem)
	message.appendChild(text)

	insertAfter(placehold.parentNode, message, placehold)

	document.title = doctitle + ' - ' + problem

	if (getObject('sRMess', 'id'))
		{
		if (getObject('sRMess', 'id').checked == true)
			{
			alert(problem)
			}
		}
}

function deleteMessage()
{
	if (getObject('problem', 'id'))
			{
			var oldMessage = getObject('problem', 'id')
			oldMessage.parentNode.removeChild(oldMessage)
			}
	document.title = doctitle
}

function screenReaderMessage()		// gives screen-reader users a tickbox to enable alert boxes for messaging changes. Requires an id="subcontent"
{
	var subcont = getObject('subcontent', 'id')

	var sRForm = document.createElement('form')
	sRForm.className = 'screenRead'
	sRForm.action = '#'
	sRForm.method = 'post'
	sRForm.id = 'sRSwitch'

	var sRLabel = document.createElement('label')
	sRLabel.htmlFor = 'sRMess'

	var sRCheck = document.createElement('input')
	sRCheck.type = 'checkbox'
	sRCheck.id = 'sRMess'
	sRCheck.name = 'sRMess'

	var sRNote = document.createTextNode('This page contains dynamic content, which a screen reader may find difficult to detect. Tick the following box if you want the page to alert you when content changes: ')

	sRLabel.appendChild(sRNote)
	sRLabel.appendChild(sRCheck)
	sRForm.appendChild(sRLabel)

	subcont.parentNode.insertBefore(sRForm, subcont)	// glues in form before 'subcontent'
}