// Validate the register for Friday Night Club form

//window.onload = windowLoaded;

var register;
var theElements; 

var colorGood = "#666666"; //Default border color for text fields
var colorBad = "#FF0000";  //Warning border color for text fields

/* Regular expressions */
var onlySpace = /^\s[\s]*\s$/; //Any space that is not surrounded by non-whitespace characters 
var twoDigit = /^\d{2}$/; //Birthday and month
var fourDigit = /^\d{4}$/; //Birth year
var zip = /^[0-9]{5}([-]?[0-9]{4})?$/; //Zipcode
var phoneNumber = /^([\(]{1}[0-9]{3}[\)]{1}[\.| |\-]{0,1}|^[0-9]{3}[\.|\-| ]?)?[0-9]{3}(\.|\-| )?[0-9]{4}$/ ; // match several phone number patterns.
var email = /^\w+[\w-\.]*\@\w+((-\w+)|(\w*))\.[a-z]{2,3}$/ //match e-mail address

var submitTest = false; //This will be true on submission, allowing certain cases of validation to work such as the parent test.

var parentFields = ['parent1','parent1Last', 'parent2', 'parent2Last']; //Parent name field ids
var parentSignature = ["parent1SignFirst", "parent1SignLast", "parent2SignFirst", "parent2SignLast"]; //Parent signature fields

//Each checkbox consists of an array of 'checkbox1' 'checkbox2' 'error message name' 
var checkBoxes = [["genderMale", "genderFemale", "genderInvalid"],
				   ["mediaYes", "mediaNo", "mediaYesInvalid"],
				   ["nameYes", "nameNo", "nameYesInvalid"],
				   ["vacYes", "vacNo", "vacYesInvalid"],
				   ["conditionYes", "conditionNo", "conditionYesInvalid"],
				   ["medicationYes", "medicationNo", "medicationYesInvalid"],
				   ["nameYes", "nameNo", "nameYesInvalid"]
				  ];
//These fields are only require if the following checkbox is checked
var ifYes = [["tetanus", "vacYes", "vacNo"],
			  ["mcondition", "conditionYes", "conditionNo"],
			  ["medication", "medicationYes", "medicationNo"]];
			  

$(document).ready(loadValidation); //Initialize the form when the DOM is loaded. 

function loadValidation()
{
register = document.forms[0]; //shortcut
theElements = register.elements; //shortcut
theFocusListener(); //assign onchage, onfocus etc to form elements
}

function clear_input()
{
	if(this.value == this.defaultValue)
	{
		this.value = "";
	}
}

function selectText()
{
	this.select();
}

function fillOnExit(textField)
{
	if(isBlank(textField))
	textField.value = textField.defaultValue;	
}

function theFocusListener()
{
    
	var grade = $('#grade').change(gradeCheck).get(0);
	if(grade)
	grade.validTest = gradeCheck; 
		
	$('#comments').focus(function(){this.select;});
	
	$('input:text')
	.focus(selectText)
	.blur(validateTextField)
	.each(function(){this.validTest = validateTextField;});

	//Add checkflip to all the checkboxes
	$('input:checkbox')
	.bind('click', checkFlip)
	.bind('click', oneChecked)
	.each(function(){this.validTest = oneChecked;});
	
	$('#authorizationYes, #liabilityYes')
	.unbind()
	.each(function(){this.validTest = checkCheck;});
}

function isBlank(textField)
{
	if(textField.value.length == 0 || onlySpace.test(textField.value) || textField.value == textField.defaultValue)
	{
		return true;
	}
	else return false; 
}

function validateTextField()
{
	
	var isValid = true;
	var isParentField = false; //is this one of the parentFields?
	if(isBlank(this)) 
	{
		isValid = false;
	}
	/* Check if it is one of the parent fields */
	for(i = 0; i < parentFields.length; i++)
	{
		if (this.id == parentFields[i])
		{
			isParentField = true;
			break;
		}
	}
	if(isParentField)
	{
			//only test on submit
			if(submitTest) isValid = parentTest();
			else isValid = true; //Skipping this one until submit
	}
	else if(ifYesTest(this)) isValid = true;
	else if(isSignature(this)) isValid = true;
	else 
	{
		//Cases for particular text field types
		var textType = this.defaultValue;
		switch (textType)
		{
			case 'email' :
			case "youth's email" :
			if(this.id == 'parent1Mail' && !parent1Test())//If its parent1Mail, only check this entry if the parent1Mail's name is filled
			{ 
				isValid = true;
				break;
			} 
			if(this.id == 'parent2Mail' && !parent2Test())//if its parent2Mail, only check this entry if the parent2Mail's name is filled
			{
				isValid = true;
				break; 
			}
			if(!email.test(this.value)) isValid = false;
			break;
			
			case 'zipcode' :
			if(!zip.test(this.value)) isValid = false;
			break;
			
			case 'phone' :
			case 'physician phone number' :
			//If its parent1Phone, only check this entry if the parent1Phone's name is filled
			if(this.id == 'parent1Phone')
			{ 
				if(!parent1Test())
				{
					isValid = true;
					break;
				}
			} 
			//if its parent2Phone, only check this entry if the parent2Phone's name is filled
			if(this.id == 'parent2Phone')
			{
				if(!parent2Test())
				{
					isValid = true;
					break;
				}
			}
			if(!phoneNumber.test(this.value)) isValid = false;
			break;
			
			case 'MM' :
			case 'DD' :
			if(!(twoDigit.test(this.value))) isValid = false; 
			break; 
			
			case 'YYYY' :
			if(!fourDigit.test(this.value)) isValid = false; 
			break;
			
			default:
			break;
		}
	}
	
	if(!isValid)
	{
		this.onchange = validateTextField;
		this.style.borderColor = colorBad;
		showInvalidError(this, 0);
		fillOnExit(this);
		return false;
	}
	else
	{
		this.style.borderColor = colorGood;
		fillOnExit(this);
		if(dateTest(this) && zipTest(this) && emTest(this) && signTest(this))  //Cases where mutliple entries have to be valid to remove warning
		{
			showInvalidError(this, 1);	
		}
		return true;
	}
	
}


/*** Some warnings cover multiple entries **/
function parent1Test() { return !(isBlank(theElements.parent1) || isBlank(theElements.parent1Last)); }
function parent2Test() { return !(isBlank(theElements.parent2) || isBlank(theElements.parent2Last)); }

function parentTest()// only warn if both parent entries are blank
{	
	if (parent1Test() || parent2Test())
	{
		theElements.parent1.style.borderColor = colorGood;
		theElements.parent1Last.style.borderColor = colorGood;
		theElements.parent2.style.borderColor = colorGood;
		theElements.parent2Last.style.borderColor = colorGood;
		return true;				//one entry is filled
	}
	else return false;
}

function isSignature(isSig)
{
	for(i = 0; i< parentSignature.length; i++)
	{
		if(isSig.id == parentSignature[i])
		{
			//if this is a parent signature field separate parent1 and parent2
			if(i < 2) 
			{
				if(parent1Test())
				return !isBlank(isSig);
				else return true;
				
			}
			else if(parent2Test()) 
			return !isBlank(isSig);
			else return true;
			
		}
		
	}
	return false;
}

function clearUnused() //On submission, clear an unused test value
{
	$('input:text').each(function(){ if(isBlank(this)) this.value = '';});
}

//Make sure each entry in in birthdate checks out before removing warning
function dateTest(isDate)
{
	if(isDate.id == 'dateDay' || isDate.id == 'dateMonth' || isDate.id == 'dateYear')
	{
		var testDay = twoDigit.test(theElements.dateDay.value);
		var testMonth = twoDigit.test(theElements.dateMonth.value);
		var testYear = fourDigit.test(theElements.dateYear.value);
		if(testDay && testMonth && testYear)
		{
			return true; //Each birthdate value is correct
		}
		else return false; //At least one value incorrect
	}
	else return true;  //Not a birthdate
	
}


//City and zip must be correct before removing warning
function zipTest(isZip)
{
	if(isZip.id == 'zip' || isZip.id == 'city')
	{
		var testZip = zip.test(theElements.zip.value);
		var testCity = !isBlank(theElements.city);
		if(testZip && testCity) return true;
		else return false;
	}
	else return true; //Not a zip or city
}
//First and last name of emergency contact must be filled
function emTest(isEM)
{
	if(isEM.id == 'emFirst' || isEM.id == 'emLast')
	{
		var testFirst = !isBlank(theElements.emFirst);
		var testLast = !isBlank(theElements.emLast); 
		if(testFirst && testLast) return true; 
		else return false;
		
	}
	else return true;
}

//First and last name of signature must be filled before removing warning
function signTest(isSign)
{
	if(isSign.id == 'signFirst' || isSign.id == 'signLast')
	{
		var testFirst = !isBlank(theElements.signFirst);
		var testLast = !isBlank(theElements.signLast);
		if(testFirst && testLast) return true;
		else return false;
	}
	else return true;
}

function gradeCheck()
{
	if(theElements.grade.selectedIndex)
	{
		showInvalidError(theElements.grade, 1);
		return true;
	}
	else 
	{
		showInvalidError(theElements.grade, 0);
		return false;
	}
}

//Some textfields require a checkbox to be checked in order to be validated
function ifYesTest(isIf)
{
	for(i = 0; i < ifYes.length; i++)
	{
		//If this field needs the checkbox to be checked in order to validate, and the checkbox is not checked then don't validate
		if(isIf.id == ifYes[i][0] && !document.getElementById(ifYes[i][1]).checked) return true; 
	}
	return false;
}


/* Test checkboxes */

function checkCheck() //Check a checkbox
{
	if(this.checked)
	{
		showInvalidError(this, 1);
		return true;
	}
	else 
	{
		showInvalidError(this, 0); 
		$(this).click(checkCheck2);
		return false;
	}
	
}
//Same as above without a return. A return false seems to cause problems when bound to button click
function checkCheck2()//Son of checkCheck
{
	if(this.checked)
	{
		showInvalidError(this, 1);
	}
	else 
	{
		showInvalidError(this, 0); 
	}
	
}

function oneChecked()
{
	//Iterate through each pair of checkboxes
	for(i = 0; i< checkBoxes.length; i++)
	{
		for(j = 0; j <= 1; j++)
		{
			var currentCheckBox = checkBoxes[i][j];
			if (this.id == currentCheckBox)
			{
				//If either checkbox is checked then we're ok
				if(theElements[checkBoxes[i][0]].checked || theElements[checkBoxes[i][1]].checked)
				{
					displayInvalid(checkBoxes[i][2], 1); //The error message id is the third element in array
					return true;
				}
				else 
				{
					displayInvalid(checkBoxes[i][2], 0);
					return false;
				}
			}
		}
	}
}
//If one checkbox is checked, uncheck the other one
function checkFlip()
{
	for(i = 0; i< checkBoxes.length; i++)
	{
		for(j = 0; j <= 1; j++)
		{
			var currentCheckBox = checkBoxes[i][j];
			if (this.id == currentCheckBox)
			{
				var otherNumber = Math.abs(j - 1); //Logical NOT 
				var otherCheckbox = theElements[checkBoxes[i][otherNumber]];
				otherCheckbox.checked = !this.checked;
			}
		}
	}
}


/******** Show html warnings **********/
function showInvalidError(formField, offSwitch)
{
	var hiddenID = null;
	switch (formField.id)
	{
		case 'parent1SignFirst':
		case 'parent1SignLast':
		case 'signFirst' : 
		case 'signLast' :
		hiddenID = "signNameInvalid";
		break;
		
		case 'parent2SignFirst':
		case 'parent2SignLast':
		hiddenID = "signName2Invalid";
		break;
		
		case 'emFirst' :
		case 'emLast' :
		hiddenID = "emNameInvalid";
		break;
		//Parent names will be tested on submit 
		case 'parent1' : 
		case 'parent1Last' :
		case 'parent2' :
		case 'parent2Last' :
		hiddenID = "parentInvalid";
		break; 
		
		case 'city' :
		case 'zip' :
		hiddenID = 'zipInvalid';
		break;
	
		case 'dateYear':
		case 'dateDay':
		case 'dateMonth':
		hiddenID = "birthdateInvalid";
		break;
		
		default: 
		hiddenID = formField.id + "Invalid";
		break;
	}
	if(hiddenID)
	displayInvalid(hiddenID, offSwitch);
	
}
//Show/hide table cells with error messages
function displayInvalid(invalidMessage, onOff)
{
	var invalidBox = document.getElementById(invalidMessage);
	var invalidRow = invalidBox.parentNode;
	
	if(onOff) 
	{
		invalidBox.style.visibility = 'hidden';
		//invalidBox.style.display = 'none';
		
		//If all of the td elements in a row are hidden, then collapse the tr
		var rowOff = true;
		var tds = invalidRow.getElementsByTagName("td");
		for(var i = 0; i < tds.length; i++)
		{
			theNode = tds[i];
			if(theNode.style.visibility == 'visible') 		//if(theNode.style.display != 'none')
			rowOff = false;		
		}
		if(rowOff) 
		{
			//if(invalidRow.style.visbilitytypeof el.style.marginLeft == 'string';
			//invalidRow.style.visibility = 'collapse';
			invalidRow.style.display = 'none';
		}
	} 
	else 
	{	
		invalidRow.style.visibility = 'visible';
		invalidBox.style.visibility = 'visible';
		try{
		invalidRow.style.display = 'table-row';
		}
		catch (e) 
		{
		invalidRow.style.display = 'block';	 //IE doesn't like table-row but displays <tr>s as block ok
		}	
	}
}

/*************** Reset and submit **************/

function resetForm()
{
	if(confirm('Do you really want to reset all form values?'))
	{
		register.reset();
		for(var i = 0; i < theElements.length; i++)
		{
			var cE = theElements[i]; //Current Element
			//showInvalidError(theElements[i], 1);
			if(cE.type == "text")
			{
				cE.style.borderColor= colorGood;
			}
		}
		hideWarnings();
		submitTest = false;
	}
}

function trySubmit()
{
	var submitOK = true;
	submitTest = true;
	//Check all form elements with error handlers
	for(var i = 0; i < theElements.length; i++)
	{	
		if(theElements[i].validTest != null)
		{
			if(theElements[i].validTest() == false)
			{
				submitOK = false;
				
			}
		}
	}
	
	if(submitOK)
	{
		//alert('submit ok');
		displayInvalid('globalError', 1); //hide main error message if present
		clearUnused(); //Clear unused parent text (looks better in the db)
		register.submit();
	}
	else 
	{
		displayInvalid('globalError', 0); //display main error message
		window.location.replace("#registerTop");
	}
}

//Hide all the warning table rows and their child table cells
function hideWarnings()
{
	var tableRows = register.getElementsByTagName("tr");
	for(var i = 0; i < tableRows.length; i++)
	{
		currentRow = tableRows[i];
		if (currentRow.className == "validate")
		{
			valCells = tableRows[i].getElementsByTagName("td");
			for(var j = 0; j < valCells.length; j++)
			{

				valCells[j].style.visibility = "hidden";
			}
			 //currentRow.style.visibility = "collapse";
			currentRow.style.display = 'none';
			
		}
	}
}
