// JavaScript Document// Form Validation Functions  v1.1.6
// http://www.dithered.com/javascript/form_validation/index.phpl
// code by Chris Nott (chris@NOSPAMdithered.com - remove NOSPAM)
//
//Not all the original functions are here, and some that are have
//minor amendments to suit nano.org.

//Switches off all buttons in the form on the page.
//Useful for preventing double submissions.
function disableForm(theform)
{
	if (document.all || document.getElementById)
	{
		for (i = 0; i < theform.length; i++)
		{
			var tempobj = theform.elements[i];
			if (tempobj.type && (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset" || tempobj.type.toLowerCase() == "image"))
				{tempobj.disabled = true;}
		}

		setTimeout('alert("Your form has been submitted.")', 4000);
		return true;
	}
	else
	{
		return false;
    }
}

// Check that an email address is valid based on RFC 822
function isValidEmail(address) {
	if (address != '' && address.search) {
      if (address.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) return true;
      else return false;
	}
	
   // allow empty strings to return true - screen these with either a 'required' test or a 'length' test
   else return true;
}

// Check that an email address has the form something@something.something
// This is a stricter standard than RFC822 which allows addresses like postmaster@localhost
function isValidEmailStrict(address) {
	if (isValidEmail(address) == false) return false;
	var domain = address.substring(address.indexOf('@') + 1);
	if (domain.indexOf('.') == -1) return false;
	if (domain.indexOf('.') == 0 || domain.indexOf('.') == domain.length - 1) return false;
	return true;
}

// Check that a string contains only letters and numbers
function isAlphanumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\w\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\W/) != -1)) return false;
	}
	return true;
}

// Check that a string contains only letters
function isAlphabetic(string, ignoreWhiteSpace) {
	
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^a-zA-Z\s]/) != -1) || (!ignoreWhiteSpace && string.search(/[^a-zA-Z]/) != -1)) return false;
	}
	return true;
}

// Check that a string contains only numbers
function isNumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\d\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1)) return false;
	}
	return true;
}

// Remove characters that might cause security problems from a string 
function removeBadCharacters(string, ignoreSpace) {
	if(string.replace && string.search)
	{
	
		if (ignoreSpace)
		{	while(string.search(/[\"\'`;]/)!=-1)
				{string = string.replace(/\"\'`;/, '');}
		}
		else if(!ignoreSpace)
		{
			while(string.search(/[\s\"\'`;]/)!=-1)
				{string = string.replace(/[\s\"\'`;]/, '');}
		}
	}
	return string;
}

// Remove all spaces from a string
function removeSpaces(string) {
	var newString = '';
	for (var i = 0; i < string.length; i++) {
		if (string.charAt(i) != ' ') newString += string.charAt(i);
	}
	return newString;
}

// Remove leading and trailing whitespace from a string
function trimWhitespace(string) {
	var newString  = '';
	var substring  = '';
	beginningFound = false;
	
	// copy characters over to a new string
	// retain whitespace characters if they are between other characters
	for (var i = 0; i < string.length; i++) {
		
		// copy non-whitespace characters
		if (string.charAt(i) != ' ' && string.charCodeAt(i) != 9) {
			
			// if the temporary string contains some whitespace characters, copy them first
			if (substring != '') {
				newString += substring;
				substring = '';
			}
			newString += string.charAt(i);
			if (beginningFound == false) beginningFound = true;
		}
		
		// hold whitespace characters in a temporary string if they follow a non-whitespace character
		else if (beginningFound == true) substring += string.charAt(i);
	}
	return newString;
}
//Here ends the borrowed code

function check_num(num)
{
	num = trimWhitespace(num);
	if(num.search(/^\+?[\d ()]*\d$/)==-1 || num.search(/\([ ]*\)/)!=-1)
		return false;
	else return true;
}

function check_chars(word, ignoreSpace)
{
	var chars = true;
	if((!ignoreSpace && (word.search(/[\s\"\'\`;]/)!=-1)) || (ignoreSpace && (word.search(/[\"\'\`;]/)!=-1)))
		chars = false;
	return chars;
}

function anything_todo(obj_type,obj_value)
//Note the reverse logic for testing the value
{
	if (document.all || document.getElementById)
	{
		for (i = 0; i < document.form.length; i++)
		{
			var tempobj = document.form.elements[i];
			if (tempobj.type && (tempobj.type.toLowerCase() == obj_type && tempobj.value.toLowerCase()!=obj_value))
			{return true;}
		}
	}
	return false;
}

function any_radios_todo()
{
	if (document.all || document.getElementById)
	{
		for (i = 0; i < document.form.length; i++)
		{
			var tempobj = document.form.elements[i];
			if (tempobj.type && (tempobj.type.toLowerCase() == "radio" && tempobj.checked==true))
			{return true;}
		}
	}
	return false;
}

function toggle_check(box)
{
	if (box.value=='on')
	{
		box.value = 'off';
	}
	else
	{
		box.value = 'on';
	}
}

//Here begin the actual form-by-form instructions
function check_reg()
{
	
	var themessage = "";
	var first    = document.form.firstname.value;
	var last     = document.form.lastname.value;
	var inits    = document.form.initials.value;
	var instit 	 = document.form.institution.value;
	var dept     = document.form.dept.value;
	var addr1    = document.form.address1.value;
	var addr2    = document.form.address2.value;
	var city	 = document.form.city.value;
	var state	 = document.form.state.value;
	var country	 = document.form.country.value;
	var post	 = document.form.postcode.value;
	var tel  	 = document.form.tel.value;
	var fax  	 = document.form.fax.value;
	var email	 = document.form.email.value;
	var pwd		 = document.form.password.value;	
	var pwd_conf = document.form.password_conf.value;
		
	if(country.search(/^[A-Z]{2}$/) == -1)
		country = "";
	
	var pta = false;

	if(first=="" || last=="" || pwd=="" || pwd_conf=="" || email=="" || instit=="" || addr1=="" || city=="" || post=="" || country=="" || (country=="US" && state=="") || tel=="")
	{
		themessage = "Please check and complete:\n";
		if(first=="")
			themessage = themessage + " - Your first name\n";
		if(last=="")
			themessage = themessage + " - Your last name\n";
		if(instit=="")
			themessage = themessage + " - Your institution's name\n";
		if(addr1=="")
			themessage = themessage + " - At least one line of your address\n";
		if(city=="")
			themessage = themessage + " - Your city\n";
		if(country=="US" && state=="")
			themessage = themessage + " - Your U.S. State\n";
		if(country=="US" && post=="")
			themessage = themessage + " - Your zip code\n";
		else if(country=="UK" && post=="")
			themessage = themessage + " - Your postcode\n";	
		else if(post=="")
			themessage = themessage + " - Your postal/zip code\n";
		if(country=="")
			themessage = themessage + " - Your country\n";
		if(tel=="")
			themessage = themessage + " - Your contact number\n";
		if(email=="")
			themessage = themessage + " - Your email address\n";
		if(pwd=="")
			themessage = themessage + " - A password\n";
		if(pwd_conf=="")
			themessage = themessage + " - Confirmation of your password\n";
	}	
	
	else//Check things
	{
	
		if(!isAlphabetic(first, true) || !isAlphabetic(last,true))
		{
			themessage = themessage + " - Your name can only contain letters\n";
			pta = true;
		}
		
		if(first.length>30 || last.length>50)
		{
			themessage = themessage + " - Your first name must be no more than 30 characters and your last name name no more than 50\n";
			pta = true;
		}
		
		if(inits != "" && inits.search(/[^A-Za-z \.]/) != -1)
		{
			themessage = themessage + " - Your initials can only contain letters, dots and spaces\n";
			pta = true;
		}
		
		if(inits.length>10)
		{
			themessage = themessage + " - Your initials must be no more than 10 characters\n";
			pta = true;
		}
		
		if(!isAlphanumeric(instit, true) || instit.length>255)
		{
			themessage = themessage + " - Your institution's name can contain at most 255 letters and numbers\n";
			pta = true;
		}
		
		if(dept != "" && (!isAlphanumeric(dept, true) || dept.length>255))
		{
			themessage = themessage + " - Your department's name can contain at most 255 letters adn numbers\n";
			pta = true;
		}
		
		if(!check_chars(addr1,true) || (addr2!="" && !check_chars(addr2,true)) )
		{
			themessage = themessage + " - Your contact address must not contain spaces any of:\n\n   \" ; \' `\n";
			pta = true;
		}
		
		if(addr1.length>255 || (addr2!="" && addr2.length>255))
		{
			themessage = themessage + " - The lines of your address can contain at most 255 characters\n";
			pta = true;
		}
		
		if(!isAlphabetic(city, true) || city.length>50)
		{
			themessage = themessage + " - Your city can contain at most 50 letters\n";
			pta = true;
		}
		
		if(!isAlphabetic(state, true) || state.length>10)
		{
			themessage = themessage + " - Your state abbreviation can contain at most 10 letters\n";
			pta = true;
		}

		if(country=="US" && (!isNumeric(post,false) || post.length!=5))//could regex this, i guess...
		{
			themessage = themessage + " - Your zip code must be a 5 digit number with no spaces\n";
			pta = true;
		}
		else if(country=="UK" && post.toUpperCase().search(/\b[A-PR-UWYZ][A-HK-Y0-9][A-HJKSTUW0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}\b/)==-1)
		{
			themessage = themessage + " - The postcode you entered is invalid\n";
			pta = true;
		}
		
		else if(!isAlphanumeric(post, true) || post.length>10)
		{
			themessage = themessage + " - Your postal/zip code can contain at most 10 letters and numbers\n";
			pta = true;
		}		
		
		if(!check_num(tel))
		{
			themessage = themessage + " - The contact number you entered is not valid\n";
			pta = true;
		}
		
		if(fax!="" && !check_num(fax))
		{
			themessage = themessage + " - The fax number you entered is not valid\n";
			pta = true;
		}
		
		if(!isValidEmailStrict(email))
		{
			themessage = themessage + " - The email address you entered is not valid\n";
			pta = true;
		}
		
		if(pwd != pwd_conf)
		{
			themessage = themessage + " - You must enter the same password in both boxes\n";
			pta = true;
		}
		
		else if(pwd == pwd_conf)
		{
			if(pwd.length<6)
			{
				themessage = themessage + " - Your password must be at least 6 characters\n";
				pta = true;
			}
			if(!check_chars(pwd))
			{
				themessage = themessage + " - Your password must not contain spaces nor any of:\n\n   \" ; \' `\n";   
				pta = true;
			}
		}
	}
	if(themessage=="")
	{
		disableForm(document.form);
		return true;
	}
	else
	{
		if(pta) {themessage = themessage + "\n   Please try again!";}
		alert(themessage);
		return false;
	}

}

function check_forum_create()
{
	var forum_name = document.form.forum_name.value;
	var themessage = "";
	var pta        = false;
	
	if(forum_name == "")
	{
		alert("Please enter a name for the forum");
		return false;
	}
	
	if (!check_chars(forum_name, true))
	{
		themessage = themessage + " - The forum's name cannot contain any of:\n\n   \" ; \' `\n";
		pta = true;
	}
	
	if(forum_name.length > 255 )
	{
		themessage = themessage + " - The forum's name can contain at most 255 characters\n";
		pta = true;
	}
	
	if(themessage == "")
	{
		disableForm(document.form);
		return true;
	}
	else
	{
		themessage = themessage + "\n   Please try again!";
		alert(themessage);
		return false;
	}
	
}

function check_login()
{
	//Just a fairly vicious function that removes offending chars from the login details
	//without warning. We should have no need to warn our users, since they cannot choose
	//such login details in the first place, and not telling hackers why it isn't working
	//seems eminently sensible to me.
	
	var name = document.form.username.value;
	var pass = document.form.password.value;
	name = removeBadCharacters(name, false);
	pass = removeBadCharacters(pass, false);
	document.form.username.value = name;
	document.form.password.value = pass;
	disableForm(document.form);
	return true;
}

function open_window(url, name, left, top, width, height, toolbar, menubar, statusbar, scrollbar, resizable)
{
  toolbar_str = toolbar ? 'yes' : 'no';
  menubar_str = menubar ? 'yes' : 'no';
  statusbar_str = statusbar ? 'yes' : 'no';
  scrollbar_str = scrollbar ? 'yes' : 'no';
  resizable_str = resizable ? 'yes' : 'no';
  window.open(url, name, 'left='+left+',top='+top+',width='+width+',height='+height+',toolbar='+toolbar_str+',menubar='+menubar_str+',status='+statusbar_str+',scrollbars='+scrollbar_str+',resizable='+resizable_str);
}