
var maxAboutMe    = 2500;
var maxInSearchOf = 2500;

var errorColor = "#ffeb79";
var whiteColor = "";

// remove leading and trailing spaces
String.prototype.trim = function() {
  return (this.replace(/^\s*(\b.*\b|)\s*$/, "$1"));
}

// Remove all spaces
String.prototype.removeSpaces = function() {
	return (this.replace(/\s/g,""));
}

function isLetter (c)
{   return (((c >= "A") && (c <= "Z")))
}
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}
function isInteger (s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }
    return true;
}

function isCanadian (s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
	if (i == 0 || i == 2 || i == 4)
        	if (!isLetter(c)) return false;
	if (i == 1 || i == 3 || i == 5)
        	if (!isDigit(c)) return false;
    }
    return true;
}

function validateNameField (theField, theName, minLen, maxLen)
{
	if (theField.value.length < minLen || theField.value.length > maxLen)
	{
		invalidTextField (theField, "Please enter a " + theName + " between " + minLen + " and " + maxLen + " characters");
		return (false);
	}
	
	if (validateTextArea(theField, theName, true) == false)
		return(false);
	
	if (reTest(theField, /^[a-zA-Z ]*$/, theName + " - letters and spaces only please") == false)
	{
		theField.focus();
		if (typeof(theField.style) != "undefined")
			theField.style.backgroundColor=errorColor;
		return (false);
	}

	return (true);
}

function reTest(theField, regex, theName)
{
	if (regex.test(theField.value) == false)
	{			
			alert("Invalid " + theName);
			theField.focus();
			return (false);
	}
	return (true);
}

function validateZip(theField, theCountry)
{
  if (theField.value.length == 0)
  {
    invalidTextField(theField, "Please enter your Postal Code.");
    return (false);
  }

  if (theCountry == "US")
  {
  	if (theField.value.length == 5 && isInteger(theField.value))
		return (true);
	invalidTextField(theField, "Invalid \"Zip\".\nU.S. zip code format - 12345");
	return (false);
  }

  if (theCountry == "CA")
  {
  	if ((theField.value.length == 3 || theField.value.length == 6) && isCanadian(theField.value))
		return (true);
	invalidTextField(theField, "Invalid \"Postal Code\".\nCanadian postal code format - A1A or A1A 2B2.");
	return (false);
  }
  return (true);
}

function isCanadianUrban(theZip)
{
	return (isCanadian(theZip) && theZip.charAt(1) != "0");
}

function CanadianFSA(theZip)
{
	return(theZip.substr(0,3));
}

// *********************************************************************************************

function invalidTextField(theField, msg)
{
	alert (msg);
	if (theField.type != "hidden")
		theField.focus();
	if (typeof(theField.style) != "undefined")
		theField.style.backgroundColor=errorColor;
}

function maxWordLength(theString)
{
	var s = theString.split(/\s/), maxLength = 0;
	for (var i = 0; i < s.length; i++)
	{
		if (s[i].length > maxLength)
			maxLength = s[i].length;
	}
	return (maxLength);
}

function validateTextArea(theField, theName, strict)
{
	var badWords  = "@|www|http|hotmail|gmail|yahoo|myspace|facebook".split("|");
	var sexWords  = "discreat|discreet|erotic|exotic|fbsm|foreplay|genital|intimate|masterbation|orgasm|penis|pleasuring|prostate|pussy|sensual|sensuel|sensuous|sucking|tantra|tantric|vagina|yoni".split("|");
	var lowercase = theField.value.toLowerCase();
	
	for (var i in badWords)
	{
		if (lowercase.indexOf(badWords[i]) >= 0)
		{
		invalidTextField (theField, "Invalid content '" + badWords[i] + "' in \"" + theName + "\".\n\nE-mail addresses, ICQ/IM IDs, WEB URLs, and telephone numbers are prohibited in your profile.\n\nOur Customer Care team personally reviews all profiles. If you wish your profile approved, please omit any prohibited items. Please see our Terms-of-Use for details.");
		return (false);
		}
	}
	
	if (strict) {
		for (var i in sexWords)
		{
			if (lowercase.indexOf(sexWords[i]) >= 0)
			{
			invalidTextField (theField, "The word \""+ sexWords[i] + "\" is not permitted in "+theName+".");
			return (false);
			}
		}
	}
	
	if (maxWordLength(theField.value) > 40)
	{
		invalidTextField (theField, "Please refrain from using uninterrupted character sequences longer than 40 characters; it really messes up the formatting.\n\nHint: Put a space after every comma and end of sentence.");
		return (false);
	}
	
	return (true);
}

function invalidField(theField, msg)
{
	alert (msg);
	theField.focus();
}

function validateEmail(theField, theName)
{
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+(([a-zA-Z0-9]{2})|com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var lowercase = theField.value.toLowerCase();
	
	if (lowercase.substr(0,4) == "www.")
	{
		invalidTextField (theField, "Invalid " + theName + ". E-mail addresses do not begin with \"www.\".");
		return (false);
	}
	
	var atSign = lowercase.indexOf("@");
	if (lowercase.charAt(0) == "." || lowercase.charAt(atSign-1) == "." || lowercase.charAt(atSign+1) == ".") {
		invalidTextField (theField, "Invalid " + theName + ": A dot (.) cannot appear before or after the name or domain.");
		return (false);
	}
	
	if (filter.test(lowercase)) return(true);
	invalidTextField (theField, "Invalid " + theName + ".");
	return (false);
}

function validateLength(theField, theName, minLen, maxLen)
{
	var value = theField.value, eMsg = "";
	if (value.length == 0 && minLen > 0)
		eMsg = "Please enter your " + theName;
	else if (value.length < minLen)
		eMsg = theName + " must be at least " + minLen + " characters. It is currently " + value.length + " characters.";
	else if (value.length > maxLen)
		eMsg = theName + " may be no longer than " + maxLen + " characters. It is currently " + value.length + " characters.";
	if (eMsg != "")
	{
		invalidTextField (theField, eMsg);
		return (false);
	}
	return true;
}

function validateComment(theField, theName, minLen, maxLen)
{
	var value = theField.value, eMsg = "";
	if (value.length == 0 && minLen > 0)
		eMsg = "An empty profile is unappealing to other members and usually skipped!\n\nPlease enter something in your \""  + theName + "\" section... a brief comment of at least " + minLen + " character is all we ask!";
	else if (value.length < minLen)
		eMsg = theName + " must be at least " + minLen + " characters. It is currently " + value.length + " characters.";
	else if (value.length > maxLen)
		eMsg = theName + " may be no longer than " + maxLen + " characters. It is currently " + value.length + " characters.";
	if (eMsg != "")
	{
		invalidTextField (theField, eMsg);
		return (false);
	}
	return true;
}

function validateMenu(theField, theName)
{
	with(theField)
	{
		if (selectedIndex == 0)
		{
			alert("Please select your " + theName);
			focus();
			return (false);
		}
	}
	return (true);
}

function trimFields(theForm)
{
	var i;
	for (i = 0; i < theForm.elements.length; i++)
	{
		if (theForm.elements[i].type == "text" || theForm.elements[i].type == "textarea" || theForm.elements[i].type == "password") 
		{
			theForm.elements[i].value = theForm.elements[i].value.trim();
			if (typeof(theForm.elements[i].style) != "undefined")
				theForm.elements[i].style.backgroundColor=whiteColor;
		}
		if (theForm.elements[i].type == "radio" || theForm.elements[i].type == "checkbox")
			if (typeof(theForm.elements[i].style) != "undefined")
				theForm.elements[i].style.backgroundColor=whiteColor;
	}
}

function validateState(theField, theName)
{
	if (theField.length <= 1)	// No States
		return (true);
	
	if (theField.selectedIndex == 0 && theField[theField.selectedIndex].value != "")
	{
		invalidField (theField, "Please select your " + theName);
		return (false);
	}
	return (true);
}

function validateAlphaField (theField, theName, minLen, maxLen, maxDigits)
{
	if (theField.value.length < minLen || theField.value.length > maxLen)
	{
		invalidTextField (theField, "Please enter a " + theName + " between " + minLen + " and " + maxLen + " letters and/or digits");
		return (false);
	}
	
	if (reTest(theField, /^[a-zA-Z0-9]+$/, theName + " - letters and digits only please") == false)
	{
		theField.focus();
		if (typeof(theField.style) != "undefined")
			theField.style.backgroundColor=errorColor;
		return (false);
	}
	
	var numDigits = 0;
	for (i = 0; i < theField.value.length; i++)
	{
		if (isDigit(theField.value.charAt(i)))
			numDigits++;
	}
	
	var numberList = "one|two|three|four|five|six|seven|eight|nine|zero".split("|");
	var lcField = theField.value.toLowerCase();
	for (d in numberList) {
		if (lcField.indexOf(numberList[d]) >= 0)
			numDigits++;
	}
	
	if (numDigits > maxDigits)
	{
		invalidTextField (theField, "Sorry, but a " + theName + " may contain at most " + maxDigits + " digits (or numbers spelled out)");
		return (false);
	}
	
	return (true);
}

function validateNumericField (theField, theName)
{
	if (theField.value.length == 0)
	{
		invalidTextField (theField, "Please enter a " + theName + " number");
		return (false);
	}
	
	if (reTest(theField, /^[0-9]+$/, theName + " - digits only please (number of hours training)") == false)
	{
		theField.focus();
		if (typeof(theField.style) != "undefined")
			theField.style.backgroundColor=errorColor;
		return (false);
	}
	return (true);
}

function collectCheckboxes(theForm, thePrefix, theDelim)
{
	var i, fullList = "";
	var preLen = thePrefix.length;
	for (i = 0; i < theForm.elements.length; i++)
	{
		if (theForm.elements[i].type == "checkbox" && theForm.elements[i].checked && theForm.elements[i].name.substr(0,preLen) == thePrefix) 
		{
			if (fullList != "")
				fullList += theDelim;
			fullList += theForm.elements[i].value;
		}
	}
	return (fullList);
}

function calcFields(theForm)
{
	theForm.ModalityList.value = collectCheckboxes(theForm, "WW", ",");
	theForm.Languages.value = collectCheckboxes(theForm, "Spoken", "");
	theForm.ActiveList.value = collectCheckboxes(theForm, "PartnerPSA", "");
	
	//theForm.ZipDisplay.value = theForm.ZipDisplay.value.toUpperCase().removeSpaces();
	//theForm.Zip.value = isCanadianUrban(theForm.ZipDisplay.value) ?	CanadianFSA(theForm.ZipDisplay.value):(theForm.ZipDisplay.value);
}

function validatePartnerForm (theForm)
{
	trimFields(theForm);
	calcFields(theForm);
	if (validateAlphaField(theForm.Username, "Username", 2, 32, 6) == false) return (false);	
	
	if (typeof(theForm.Password) != "undefined") {
		if (validateAlphaField(theForm.Password, "Password", 2, 16, 99) == false) return (false);
		if (String(theForm.Username.value).toLowerCase() == String(theForm.Password.value).toLowerCase()) {
			alert("For your security, your PASSWORD cannot be the same as your USERNAME.");
			theForm.Password.focus();
			return (false);
		}
	}
	
	//if (validateLength(theForm.Email, "E-mail", 2, 64) == false) return (false);
	//if (validateEmail(theForm.Email, "E-mail") == false) return (false);
	if (typeof(theForm.Sex) != "undefined" && validateRadio(theForm.Sex, "Gender (M/F)") == false) return (false);
	
	if (typeof(theForm.PartnerSex) != "undefined" && validateRadio(theForm.PartnerSex, "Bodyworker's desired Gender (M/F/E)") == false) return (false);

	if (typeof(theForm.ProAm) != "undefined" && validateRadio(theForm.ProAm, "Therapist, Student, or Enthusiast Status") == false) return (false);
	
	if (validateNumericField(theForm.FormalTraining, "Formal Training (hours)") == false) return (false);
	//if (validateMenu(theForm.Experience, "Bodywork Experience (in years)") == false) return (false);
	
	if (typeof(theForm.Formal) != "undefined" && theForm.Formal.checked) {
		if (validateLength(theForm.School1, "Bodywork school name - where you received your formal bodywork training.\r\n\r\nIf you've not attended a bodywork school, uncheck the \"FORMAL training\" checkbox.", 2, 128) == false) return (false);
		if (validateTextArea(theForm.School1, "School Name", true) == false) return (false);
		
		if (typeof(theForm.SchoolLocation) != "undefined" && theForm.School1.value != "")
			if (validateLength(theForm.SchoolLocation, "School Location", 2, 128) == false) return (false);
		
		if (typeof(theForm.SchoolLocation) != "undefined" && validateTextArea(theForm.SchoolLocation, "School Location", true) == false) return (false);

		if (typeof(theForm.FormalTraining) != "undefined") {
			var FT = parseInt(theForm.FormalTraining.value, 10);
			if (isNaN(FT)) {
				invalidTextField(theForm.FormalTraining, "Hours of Formal Training: invalid number - \""+String(theForm.FormalTraining.value)+"\".");
				return (false);
			}
			if (FT <= 0) {
				invalidTextField(theForm.FormalTraining, "\"Hours of Formal Training\" should be greater than 0 if you've received formal training.\r\n\r\n(If you've NOT attended a bodywork school, uncheck the \"FORMAL training\" checkbox.)");
				return (false);
			}
		}
		
		
		
	}

	//if (validateTextArea(theForm.Memberships, "Memberships", true) == false) return (false);
	
	if (validateCheckboxGroup(theForm, "WW", "Bodywork Modality") == false) return (false);
	
	if (validateMenu(theForm.Birthyear, "Birthyear. (Month/day are optional.)\n\nYour birthdate is never displayed but is needed for age-range searches") == false) return (false);
	
	if (validateCheckboxGroup(theForm, "Spoken", "Language Spoken") == false) return (false);
	
	if (typeof(theForm.AboutMe) != 'undefined') {
		if (validateComment(theForm.AboutMe, "More about me", 50, maxAboutMe) == false) return (false);
		if (validateTextArea(theForm.AboutMe, "More about me", true) == false) return (false);
	}
	
	// if (validateLength(theForm.InSearchOf, "I'm in Search of", 0, 2500) == false) return (false);

	return true;
}

function usernameValid(theUsername, theEmail)
{
	var u = theUsername.value.toLowerCase();
	var e = theEmail.value.toLowerCase();
	var ue = e.split("@");
	if (ue.length != 2) {
		invalidTextField(theEmail, "Invalid e-mail address");
		return(false);
	}
	var namepart = ue[0];
	var domainpart = ue[1].replace(/\..*/,"");
	if (u == namepart || (namepart.length >= 4 && u.indexOf(namepart) >= 0))
	{
		invalidTextField(theUsername, "For privacy and confidentiality,\r\n\r\nyour username should not be or contain your e-mail address name ('"+namepart+"').\r\n\r\nPlease select a different username.");
		return(false);
	}

	if (u == domainpart)
	{
		invalidTextField(theUsername, "For privacy and confidentiality,\r\n\r\nyour username should not be your e-mail address domain ('"+domainpart+"').\r\n\r\nPlease select a different username.");
		return(false);
	}
	return(true);
}

function validateUsernameForm(theForm)
{
	trimFields(theForm);
	
	if (validateAlphaField(theForm.Username, "Username", 2, 32, 5) == false) return (false);
	if (validateTextArea(theForm.Username, "Username", true) == false) return (false);
		
	if (validateLength(theForm.Email, "E-mail", 2, 64) == false) return (false);
	
	if (validateEmail(theForm.Email, "E-mail") == false) return (false);
	
	if (usernameValid(theForm.Username, theForm.Email) == false) return (false);
	
	if (!theForm.Affirm.checked) {
		alert("You must AGREE to the items stated to register.\r\n\r\nClick the CHECKBOX next to 'I affirm that:' if you agree to the items stated and wish to register.");
		theForm.Affirm.focus();
		return (false);
	}

	return true;
}

