var validation_information = {
	general_form: {
		first_name: {test: ValidName, message: "You must enter a valid first name."},
		last_name: {test: ValidName, message: "You must enter a valid last name."},
		email_address: {test: ValidEmailAddress, message: "You must enter a valid e-mail address."},
		age_group: {test: ValidNotBlank, message: "You must select an item from the list."},
		station_website: {test: ValidWebsite, message: "You must enter a valid website."},
		city: {test: ValidName, message: "You must enter a city."},
		region: {test: ValidNotBlank, message: "You must select an item from the list."},
		message: {test: ValidNotBlank, message: "You must enter a message."},
		service_rating: {test: ValidNotBlank, message: "You must select an item from the list."}
	},
	sales_form: {
		first_name: {test: ValidName, message: "You must enter a valid first name."},
		last_name: {test: ValidName, message: "You must enter a valid last name."},
		email_address: {test: ValidEmailAddress, message: "You must enter a valid e-mail address."},
		company_name: {test: ValidCorporateName, message: "You must enter a valid company name."},
		phone_number: {test: ValidPhoneNumber, message: "You must enter a valid phone number. If you are outside the US or Canada, please enter a ‘+’, then your country code and then your phone number."},
		company_website: {test: ValidWebsite, message: "You must enter a valid website."},
		project_type: {test: ValidNotBlank, message: "You must select an item from the list."},
		budget: {test: ValidNotBlank, message: "You must select an item from the list."},
		time_frame: {test: ValidNotBlank, message: "You must select an item from the list."},
		notes: {test: ValidNotBlank, message: "You must enter a message."}
	},
	support_form: {
		first_name: {test: ValidName, message: "You must enter a valid first name."},
		last_name: {test: ValidName, message: "You must enter a valid last name."},
		email_address: {test: ValidEmailAddress, message: "You must enter a valid e-mail address."},
		city: {test: ValidName, message: "You must enter a city."},
		call_letters: {test: ValidCallLettersOrWebsite, message: "You must enter valid call letters for the station OR the station's web site. Call letters are usually in the format WKRPFM or WKRPAM. If you cannot find or do not know the station's call letters, please enter their full website address."},
		location: {test: ValidNotBlank, message: "You must select an item from the list."},
		operating_system: {test: ValidNotBlank, message: "You must select an item from the list."},
		internet_connection: {test: ValidNotBlank, message: "You must select an item from the list."},
		client: {test: ValidNotBlank, message: "You must select an item from the list."},
		media_player: {test: ValidNotBlank, message: "You must select an item from the list."},
		anti_virus: {test: ValidCorporateName, message: "You must enter a valid product name. If you don't have anti-virus software, enter \"none\"."},
		notes: {test: ValidNotBlank, message: "You must enter a message."}
	},
	open_entry: {
		author: {test: ValidName, message: "You must enter a valid name."},
		title: {test: ValidNotBlank, message: "You must enter a title."},
		text: {test: ValidNotBlank, message: "You must enter some text."},
		keywords: {test: ValidNotBlank, message: "You must enter some keywords."}
	},
	entry_list: {
		entry: {test: ValidNotBlank, message: "You must select an item from the list."}
	}
};

var messages = [];

function SetupForms() {
	for (var form_id in validation_information) {
		var form = document.getElementById(form_id);
		if (form != null) {
			form.onsubmit = function() {
				return Validate(this) && AdditionalValidation(this);
			};
			AdditionalSetup(this);
		}
	}
}

function AdditionalSetup(form) {
	
}
function AdditionalValidation(form) {
	switch (form.id) {
		case "entry_list":
			if (document.getElementById('operation_delete').checked) {
				return confirm("You have selected that you would like to delete\na blog entry. Are you SURE that you want to do\nthis? This operation cannot be undone.");
			}
			if (document.getElementById('operation_touch').checked) {
				return confirm("You have selected that you would like to update\nthe timestamps on a blog entry. This will place\nthe entry at the top of the list of blog\nentries. Are you SURE that you want to do this?\nThis operation cannot be undone.");
				return false;
			}
			return true;
		case "open_entry":
			if (document.getElementById("entry_id") == null) {
				
				// New entry
				if (document.getElementById("display_no").checked) {
					return confirm("You have created a new entry, but you have not activated it. If you would like to activate it, cancel this operation, select the “Yes” option under “Active:” and resubmit the data. Otherwise, click OK to activate this entry at a later date.");
				}
				return true;
			}
			
			// Old Entry
			var display_no = document.getElementById('display_no');
			if (display_no.defaultChecked != display_no.checked) {
				return confirm("You are about to " + (display_no.checked ? "deactivate" : "activate") + " this entry. Are you sure?");
			}
			return true;
			
		default:
			return true;
	}
}

function Validate(form) {

	// We need to get rid of any messages that are already out there.
	var old_messages = messages;
	for (var i = old_messages.length - 1; i >= 0; i--) { // We have to reverse iterate. Otherwise, it will skip every other one.
		old_messages[i].parentNode.removeChild(old_messages[i]);
	}

	messages = [];
	
	// Validate each field.
	var all_valid = true;
	var first_invalid = false;
	for (var id in validation_information[form.id]) {
		if (!ValidateField(id)) {
			all_valid = false;
			
			if (first_invalid === false) {
				first_invalid = id;
			}
		}
	}
	
	if (!all_valid) {
		alert("Some of the information that you entered in the\nform is invalid. Please look over your information\nand ensure that it is correct before resubmiting.");
		document.getElementById(first_invalid).focus();
	}
	
	return all_valid;
}
function ValidateField(element_id) {
	var element = document.getElementById(element_id);
	element.value = element.value.trim();
	
	var rule = validation_information[element.form.id][element.id].test;
	if (rule != undefined) {
		var is_valid = rule(element);
		
		var labels = document.getElementsByTagName("label");
		for (var i = 0; i < labels.length; i++) {
			if (labels[i].getAttribute("for") == element_id) {
				labels[i].className = is_valid ? "" : "Invalid";
				break;
			}
		}
		
		if (is_valid) {
			element.className = "";
			return true;
		}
		element.className = "Invalid";
		
		var message_text = validation_information[element.form.id][element.id].message;
		if (message_text != undefined && message_text != "" && message_text != null) {
			message = document.createElement("div");
			message.appendChild(document.createTextNode(validation_information[element.form.id][element.id].message));
			message.className = "Invalid";
			element.parentNode.appendChild(message);
			messages.push(message);
		}
		
		return false;
	}
	return true;
}
function ValidName(element) {
	return /^[^!"#$%()*+0123456789:;<=>?@[\]^_`{|}~]+$/.test(element.value);
}
function ValidCorporateName(element) {
	return /^[^"#%()*+<=>?[\]^_`{|}~]+$/.test(element.value);
}
function ValidEmailAddress(element) {
	return /^[A-Za-z0-9\-_.]+@[A-Za-z0-9\-.]+\.([A-Za-z]{2}|biz|com|edu|info|name|net|org|pro|aero|asia|cat|coop|edu|gov|int|jobs|mil|mobi|museum|tel|travel)$/.test(element.value);
}
function ValidWebsite(element) {
	
	// Examples that work:
	// http://www.example.com/
	// http://www.example.com:8080/
	// http://www.example.com/directory/
	// http://www.example.com/directory/subdirectory/
	// http://www.example.com/directory/subdirectory/page.html
	// http://www.example.com/directory/subdirectory/page.html#Anchor
	// http://www.example.com/directory/subdirectory/exec.php?search_term=whatnot
	// http://www.example.com/directory/subdirectory/exec.php?search_term=whatnot&search_type=video
	// https://www.example.museum:8080/directory/subdirectory/exec.php?search_term=whatnot&search_type=video&client=Firefox#Anchor
	
	// Yes, it is complicated. URLs usually are.
	return /^(http|https|HTTP|HTTPS):\/\/[A-Za-z0-9\-.]+\.([A-Za-z]{2}|biz|com|edu|info|name|net|org|pro|aero|asia|cat|coop|edu|gov|int|jobs|mil|mobi|museum|tel|travel)(:[0-9]+)?(\/[A-Za-z0-9\/\-.]*)?(\?([^&=]+(=[^&=]*))(&[^&=]+(=[^&=]*))*)?(#[A-Za-z][A-Za-z0-9\-_:.]*)?$/.test(element.value);
}
function ValidPhoneNumber(element) {
	NormalisePhoneNumber(element);
	
	// Non-NANP phone numbers don't get checked.
	return /^(\([2-9][0-8][0-9]\) [2-9][0-9]{2}-[0-9]{4}|\+.*)$/.test(element.value);
}
function NormalisePhoneNumber(element) {
	
	// Blank values don't get formatted.
	if (element.value.length <= 0) {
		return;
	}
	
	// Non-NANP phone numbers don't get formatted yet, and as much as we get international phone numbers, they never will.
	if (element.value.charAt(0) == "+" && element.value.charAt(1) != "1") {
		return;
	}
	
	var numbers = StripNonNumeric(element.value);
	element.value = numbers.replace(/^1?([0-9]{0,3})([0-9]{0,3})([0-9]{0,4})$/, "($1) $2-$3");
}	
function ValidCallLettersOrWebsite(element) {
	return /^[A-Z0-9\-]{3,7}$/.test(element.value) || ValidWebsite(element);
}
function ValidNotBlank(element) {
	return element.value.length > 0;
}
function ValidNone(element) {
	return true;
}

function StripNonNumeric(string) {
	
	var buffer = "";
	for (var i = 0; i < string.length; i++) {
		var character = string.charAt(i);
		if (character >= "0" && character <= "9") {
			buffer += character;
		}
	}
	return buffer;
	
}

function GeographicSwitch(in_united_states_id, list_id, label_id) {
	var in_united_states = document.getElementById(in_united_states_id).checked;
	var list_element = document.getElementById(list_id);
	var label_element = document.getElementById(label_id);
	
	// Remove what's currently there.
	while (list_element.firstChild != undefined) {
		list_element.removeChild(list_element.firstChild);
	}
	while (label_element.firstChild != undefined) {
		label_element.removeChild(label_element.firstChild);
	}
	
	var label_url = "";
	var label_alt_text = "";
	var regions = [];
	
	if (in_united_states) {
		label_url = "state_youre_listening_from.png";
		label_alt_text = "State You're Listening From:";
		regions = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Massachusettes", "Maryland", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tenessee", "Texas", "Utah", "Vermont", "Virgina", "Washington", "West Virginia", "Wisconsin", "Wyoming", "American Samoa", "Guam", "Northern Mariana Islands", "Puerto Rico", "Virgin Islands"];
	}
	else {
		label_url = "country_youre_listening_from.png";
		label_alt_text = "Country You're Listening From:";
		regions = ["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burma", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Central African Republic", "Chad", "Chile", "China", "Colombia", "Comoros", "Congo, Republic of", "Congo, Democratic Republic of", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djbouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Fiji", "Finland", "France", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Greece", "Grenada", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Ivory Coast", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, North", "Korea, South", "Kuwait", "Kyrgystan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Morocco", "Mozambique", "Namibia", "Nauru", "Nepal", "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", "Qatar", "Romania", "Russia", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "São Tomé and Príncipe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "Spain", "Sri Lanka", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Yemen", "Zambia", "Zimbabwe"];
	}
	
	var label_image = document.createElement("img");
	label_image.setAttribute("src", "/images/common/form_labels/" + label_url);
	label_image.setAttribute("alt", label_alt_text);
	
	label_element.appendChild(label_image);
	
	var first_option = document.createElement("option");
	first_option.setAttribute("value", "");
	first_option.setAttribute("disabled", "disabled");
	first_option.setAttribute("selected", "selected");
	first_option.appendChild(document.createTextNode("- Select One -"));
	list_element.appendChild(first_option);
	
	for (var i = 0; i < regions.length; i++) {
		var option = document.createElement("option");
		option.setAttribute("value", regions[i]);
		option.appendChild(document.createTextNode(regions[i]));
		list_element.appendChild(option);
	}
}