var maxWhyDiet    = 2500;
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 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 invalidField(theField, msg)
{
	alert (msg);
	theField.focus();
}

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)
{
	var badWords  = "@|www|http|hotmail|gmail|yahoo|myspace".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 (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 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... " + minLen + " characters 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 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) == 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 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.Languages.value = collectCheckboxes(theForm, "Spoken", "");
	
	//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 (validateRadio(theForm.Sex, "Gender (M/F)") == false) return (false);
	
	if (validateRadio(theForm.PartnerSex, "Dating/Romance partner's gender (M/F/E/N)") == false) return (false);
	if (validateRadio(theForm.Friendship, "Friend/PenPal gender (M/F/E/N)") == false) return (false);
	
	//if (validateNameField(theForm.theCity, "City", 1, 40) == false) return (false);
	//if (validateState(theForm.theState, "State") == false) return (false);
	//if (validateZip(theForm.ZipDisplay, theForm.theCountry.options[theForm.theCountry.selectedIndex].value) == false) return (false);

	if (validateMenu(theForm.Birthyear, "Birth year.\n\nYour birthdate is never displayed but is needed for age-range searches and your astrological sign determination.") == false) return (false);
	if (validateMenu(theForm.Birthmonth, "Birth month.\n\nYour birthdate is never displayed but is needed for age-range searches and your astrological sign determination.") == false) return (false);
	if (validateMenu(theForm.Birthday, "Birth day.\n\nYour birthdate is never displayed but is needed for age-range searches and your astrological sign determination.") == false) return (false);
	
	if (validateMenu(theForm.Height, "Height") == false) return (false);
	
	// if (validateMenu(theForm.Weight, "Weight") == false) return (false);
	if (validateMenu(theForm.Hair, "Hair Color") == false) return (false);
	if (validateMenu(theForm.Eyes, "Eye Color") == false) return (false);
	if (validateMenu(theForm.Body, "Body Type") == false) return (false);
	
	if (validateRadio(theForm.Diet, "Diet") == false) return (false);
	
	if (validateMenu(theForm.Relationship, "Relationship Status") == false) return (false);
	if (validateMenu(theForm.Occupation, "Occupation") == false) return (false);
	if (validateMenu(theForm.HaveChildren, "Have Children") == false) return (false);
	if (validateMenu(theForm.WantChildren, "Want Children") == false) return (false);
	if (validateMenu(theForm.Smoking, "Smoking") == false) return (false);
	if (validateMenu(theForm.Drinking, "Drinking") == false) return (false);
	//if (validateMenu(theForm.Education, "Education") == false) return (false);
	if (validateMenu(theForm.Ethnicity, "Ethnicity") == 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") == false) return (false);
	}
	if (typeof(theForm.InSearchOf) != 'undefined') {
		if (validateComment(theForm.InSearchOf, "I'm in Search of", 50, maxInSearchOf) == false) return (false);
		if (validateTextArea(theForm.InSearchOf, "I'm in Search of") == 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 (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);

	return true;
}

