﻿// JavaScript Document

//following function called when submit button on page is clicked, 
//function collects the name of each field into an array, calls the validate() function
//and creates a pop-up message if validate() returns a value
function startValidate(theForm) {
	
	var reason = "";
	var functionList=new Array();
	var formList=new Array();
	var writeIn = "";
	var format = "";
	var cDate = new Date();
	var wDay=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
	var cMonth=new Array("01","02","03","04","05","06","07","08","09","10","11","12");
	
	//following loops through the elements of the form and places the name in the formList array
	//secondly calls the validate() function to validate each field, appends and returns the result as "reason" 
	for(var i=0;i<document.emailerForm.length-8;i++)
	{
		formList.push(document.emailerForm.elements[i].name);
		reason += validate(formList[i]);
	}
	
	//checks if "reason" has any result, if not, proceed with form submission
	//else an alert box pops-up displaying the fields with errors
	if(reason != "")
	{
		if(document.emailerForm.title.match("_es"))
		{
			alert(unescape('Por favor revise la corrección de los campos siguientes.\nLos campos marcados con (*) son indispensables para el envío:\n\n')+reason);
		} else {
			if(document.emailerForm.title.match("_fr"))
			{
				alert("Veuillez réviser et corriger, s'il y a lieu, les champs suivants.\nLes champs marqués d'un (*) sont obligatoires:\n\n"+reason);
			} else {
				if(document.emailerForm.title.match("_pl"))
				{
					alert("Polish Errors");
				} else {
					if(document.emailerForm.title.match("_en"))
					{
						alert("Please review the following fields for correction.\nThe fields marked with (*) are required for submission:\n\n"+reason);
					}
				}
			}
		}
		return false;
	} else {
		
		//writeIn = output message to be displayed. Creates a top section that displays a collection of specific form field values
		//based on the Forms tag title values. The "+=" appends the value as it loops through all the form elements.
		writeIn += "<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><title></title></head><body style='padding: 0px; margin: 0px;'><table width='450px' cellpadding='5' cellspacing='0' border='0'><tr><td colspan='2'><p><strong>My contact information:</strong></p><p><strong>";
		//output information into a specific format in the email
		if(document.emailerForm.title != "")
		{
			format = formatOutPut();
		}
		writeIn += format+"</p><p>Date of Request: "+cMonth[cDate.getMonth()]+"/"+cDate.getDate()+"/"+cDate.getYear()+"</strong></p><p>&nbsp;</p></td></tr>";
		//output all fields and values into one table
		for(var i=0;i<document.emailerForm.length-8;i++)
		{
			if(document.emailerForm.elements[i].type == "checkbox" && document.emailerForm.elements[i].checked == true)
			{
				writeIn += "<tr><td width='170px' valign='top' style='border: 1px solid #333333;'><span style='font-weight: bold;'>"+document.emailerForm.elements[i].title+":</span></td><td valign='top'>Member</td></tr>";
			} else {
				if(document.emailerForm.elements[i].multiple)
				{
					writeIn += "<tr><td width='170px' valign='top' style='border: 1px solid #333333;'><span style='font-weight: bold;'>"+document.emailerForm.elements[i].title+":</span></td><td valign='top'>"
					for(var o=0;o<document.emailerForm.elements[i].length;o++)
					{
						if(document.emailerForm.elements[i].options[o].selected)
						{
							writeIn += document.emailerForm.elements[i].options[o].value+"<br />";
						}
					}
					writeIn += "</td></tr>";
				} else {
					writeIn += "<tr><td width='170px' valign='top' style='border: 1px solid #333333;'><span style='font-weight: bold;'>"+document.emailerForm.elements[i].title+":</span></td><td valign='top'>"+document.emailerForm.elements[i].value+"</td></tr>";
				}
			}
		}
		writeIn += "</table></body></html>";
		//document.write(writeIn);
		document.emailerForm["emailBody"].value = writeIn;
	}
	return true;
}
//end startValidate

//start validate()
function validate(fld)
{
	var error = "";
	var validTxtChar = /^[a-zA-z -.ŒœÀÁÆÇÈÉÌÍÐÑÒÓÕÙÚÜÞàáäåæçèéëìíðñòóõöùúüþÐ]+$/;
	var validNumChar = /^[0-9() -.]+$/;
	var validNumTxtChar = /^[0-9a-zA-Z „Œœ¡«»¿ÀÁÆÇÈÉÌÍÐÑÒÓÕÙÚÜÞàáäåæçèéëìíðñòóõöùúüþCcÐ]+$/;
	var illegalChar = /[\(\)\<\>\,\;\:\\\"\[\]]/;
	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/
	var index=document.emailerForm[fld].selectedIndex;
	
	//begin validation of member checkfield
	if(document.emailerForm["Knight"].checked && document.emailerForm["Squire"].checked){
		error = "Please choose one box -- Knight of Columbus or Columbian Squire.\n";
		document.emailerForm["Knight"].checked = false;
		document.emailerForm["Squire"].checked = false;
	} else {
	//begin validation of select type fields
	if(document.emailerForm[fld].type == "select-one")
	{
		//if select field is required and value is "default" return error
		if(document.emailerForm[fld].options[index].value == "default")
		{
			document.emailerForm[fld].style.background = '#ffff99';
			error = document.emailerForm[fld].title+"\n";
		} else {
			if(document.emailerForm[fld].options[index].value == "HomePhoneOpt" && document.emailerForm["HomePhone"].value == "")
			{
				document.emailerForm["HomePhone"].style.background = '#ffff99';
				error = document.emailerForm["HomePhone"].title+'\n';
			} else {
				if(document.emailerForm[fld].options[index].value == "WorkPhoneOpt" && document.emailerForm["WorkPhone"].value == "")
				{
					document.emailerForm["WorkPhone"].style.background = '#ffff99';
					error = document.emailerForm["WorkPhone"].title+'\n';
				} else {
					if(document.emailerForm[fld].options[index].value == "EmailOpt" && document.emailerForm["Email"].value == "")
					{
						document.emailerForm["Email"].style.background = '#ffff99';
						error = document.emailerForm["Email"].title+'\n';
					} else {
						document.emailerForm[fld].style.background = '#ffffff';
					}
				}
			}
		}
	} else {
	//end validation of select type field
		//begin validation of all other type fields
		//below checks for the following conditions: 
		//- if field is "REQ" and field is blank
			if(document.emailerForm[fld].value == "" && document.emailerForm[fld].name.match("REQ"))
			{
				document.emailerForm[fld].style.background = '#ffff99';
				error = document.emailerForm[fld].title+'\n';
			} else {
			if(document.emailerForm[fld].value != "" && fld.match("Name") && fld.match("City") && fld.match("State") && fld.match("Country") && !document.emailerForm[fld].value.match(validTxtChar))
			{
				document.emailerForm[fld].style.background = '#ffff99';
				error = document.emailerForm[fld].title+'\n';
			} else {
				if(document.emailerForm[fld].value != "" && fld.match("Address") && fld.match("PreferredTime") && fld.match("MemberNum") && fld.match("CouncilNum") && !document.emailerForm[fld].value.match(validNumTxtChar))
				{
					document.emailerForm[fld].style.background = '#ffff99';
					error = document.emailerForm[fld].title+'\n';
				} else {
					if(document.emailerForm[fld].value != "" && fld.match("Post"))
					{
						error = validatePost(document.emailerForm[fld]);
					} else {
						if(document.emailerForm[fld].value != "" && fld.match("Phone"))
						{
							error = validatePhone(document.emailerForm[fld]);
						} else {
							if(document.emailerForm[fld].value != "" && fld.match("Email"))
							{
								error = validateEmail(document.emailerForm[fld]);
							} else {
								if(document.emailerForm[fld].value != "" && fld.match("MemberNum") || document.emailerForm[fld].value != "" && fld.match("CouncilNum"))
								{	
									error = validateNum(document.emailerForm[fld]);
								} else {
									document.emailerForm[fld].style.background = '#ffffff';
								}
							}
						}
					}
				}
			}	
		}
	}
	}
	return error;
}

function trim(s)
{
	return s.replace(/^\s+|\s+$-()/, '');
}

function validatePost(fld)
{
	var error="";
	var validPostChar = /^[0-9a-zA-Z -]+$/;
	
	if(!fld.value.match(validPostChar))
	{
		fld.style.background = '#ffff99';
		error = 'Zip/Postal Code';
	} else {
		fld.style.background = '#ffffff';	
	}
	return error;
}

function validateEmail(fld) {
   	var error="";
   	var tfld = trim(fld.value);                 // value of field with whitespace trimmed off
   	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
   	var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\ ]]/ ;
   
   	if (!emailFilter.test(tfld)) {              //test email for illegal characters
       	fld.style.background = '#ffff99';
       	error = "E-mail address\n";
   	} else if (fld.value.match(illegalChars)) {
       	fld.style.background = '#ffff99';
       	error = "E-mail address\n";
   	} else {
       	fld.style.background = '#ffffff';
   	}
   	return error;
}

function validatePhone(fld)
{
	var error = "";
	var tfld = trim(fld.value);
	var validChar=/^[0-9-() .]+$/;
	
	if(fld.name == "HomePhone" && fld.value.length < 7)
	{
		fld.style.background = '#ffff99';
		error = "Home phone\n";
	} else {
		if(fld.name == "WorkPhone" && fld.value.length < 7)
		{
			fld.style.background = '#ffff99';
			error = "Work phone\n";
		} else {
			if(!fld.value.match(validChar))
			{
				fld.style.background = '#ffff99';
				error = "Phone# has invalid characters\n";
			} else {
				fld.style.background = '#ffffff';
			}
		}
	}
	return error;
}

function validateNum(fld)
{
	var error="";
	var validChar=/^[0-9]+$/;
	
	if(!fld.value.match(validChar))
	{
		fld.style.background = '#ffff99';
		error = fld.title+" contains invalid characters";
	} else {
		fld.style.background = '#ffffff';	
	}
	return error;
}

//following formats the information submitted into an address label 
//displayed at the top of the email, returns this value back to startValidate() function
function formatOutPut()
{
	var str = "";
	var title = document.emailerForm["Title"].value;
	var middleName = document.emailerForm["MiddleName"].value;
	var address2 = document.emailerForm["Address2"].value;

	str += (title == "default" ? "" : title + " ") + document.emailerForm["REQFirstName"].value + " " + 
	(middleName == "" ? "" : middleName + " ") + 
	document.emailerForm["REQLastName"].value + "<br />" + 
	document.emailerForm["REQAddress1"].value + "<br />" + 
	(address2 == "" ? "" : address2 + "<br />") + document.emailerForm["REQCity"].value + ", " + 
	document.emailerForm["REQState"].value + " " + 
	document.emailerForm["REQPostalCode"].value + "<br />" + 
	document.emailerForm["REQCountry"].value + "<br /><br />";
	

	return str;
}