// JavaScript Document

var CurLeftPosition;
var CurLink;
var Interval;
var FinalPos;

// Menu array = (menu name, start position)
var menus = new Array("homeMenu", "718px", 
											"whatIsMenu", "575px", 
											"commonIssuesMenu", "539px",
											"workshopsMenu", "650px");

function showMenu (element, slideAmount)
{	
	for (menu = 0; menu < menus.length; menu=menu+2)
	{		
		if ((menus[menu]) == element)
		{			
			document.getElementById(menus[menu]).style.visibility = "visible";
			slideLeft(menus[menu], slideAmount);
		}
		else 
		{
			document.getElementById(menus[menu]).style.visibility = "hidden";
			document.getElementById(menus[menu]).style.left = menus[menu + 1];
		}
	}
}

function slideLeft(selectedLink, endPos)
{
	FinalPos = endPos;
	
	clearInterval(Interval);
  CurLink = document.getElementById(selectedLink);
	CurLeftPosition = CurLink.style.left;
  CurLeftPosition = CurLeftPosition.substring(0,CurLeftPosition.length-2);

  Interval = setInterval("show(FinalPos)", 1); // FinalPos must be declared a global variable
}

function show(stopPos)
{
	if ( (CurLeftPosition) >= stopPos ) 
	{
   CurLeftPosition = CurLeftPosition - 4;
   CurLink.style.left = CurLeftPosition + "px"; 
	} 
}

function swapLinkCircle(element)
{
	document.getElementById(element).style.backgroundImage = "url(images/blueCircle.png)";
}

function restoreLinkCircle(element, color)
{
	switch (color)
	{
		case "black":
			document.getElementById(element).style.backgroundImage = "url(images/blackCircle.png)";
			break;
		case "green":
			document.getElementById(element).style.backgroundImage = "url(images/greenCircle.png)";
			break;		
	}
}

function wait(mills)
{
	//Suspend javascript (and HTML) execution
	var date = new Date();
	var curDate = null;
	
	do { curDate = new Date(); }
	while(curDate-date < mills);
}

function eMailLink (n,sl,tl)
{
	var subject = "The Intimacy Institute";
	/* 
		Split the 3 variables into an array of characters (use empty string: "", delimiter),  
	  reverse the character array and re-join them into a new string.
	*/
	var name = n.split("").reverse().join("");
	var secondLevel = sl.split("").reverse().join("");
	var topLevel = tl.split("").reverse().join("");
	
	/*
		Create the link string and write it to the document using the object string 
	  Link() method. The method takes a hypertext link as an argument, in this case 
		the 'mailto:' protocol.
	*/	
	linkName = name + "@" + secondLevel + "." + topLevel; 
	document.write(linkName.link("mailto:" + name + "@" + secondLevel + "." + topLevel + "?subject=" + subject));	
}

function lengthCheck(strAddress, intMinLength, intMaxLength)
{

	strLength = strAddress.length;
	
	if (strLength < intMinLength || strLength > intMaxLength)
	  return false;
		
	return true;
}
function checkLocalPortion(strAddress)
{
	//Local parts:
	//1. may be strings separated by periods
	//2. may be quoted characters or strings except "\"
	//3. may be letters, digits, and characters: ! # $ % & ' * + - / = ? ^ _ ` { | } ~ .
	//4. may be combinations of 1, 2, and 3.
	//5. cannot start or end with "." or contain periods two or more times consecutively

	//  Don't forget to remove beginning and ending spaces in strAddress
	
	var periodPatternCheck = /^\.|\.$/;
	var quotePatternCheck  = /"(.*){1,62}"/; //This does not take into account that  																					 																					 //backslash double quotes (\") must be a 
																					 //matching pair while inside a double quote pair
	var localPatternCheck  = /^[A-Za-z0-9!#$%^&\+_\*-\/=~`'\|?\{\.\}]{1,64}$/;
	var quotePosition = strAddress.indexOf("\"");
	
	var arrQuotedString = new Array(); //Local address quoted array string initial index
	var arrLocalString  = new Array(); //Local address non quoted array strings

  //Check length of local part. Must be up to 64 characters long.	
	if ( !lengthCheck(strAddress,1,64) )
	  return false;
	
	//Check for a local addresses that start or end	with periods
	if ( strAddress.match(periodPatternCheck) != null )
	  return false;

	//Spit local address into quoted and non quoted string pieces 
	if ( quotePosition != -1 ) 
		{
			arrLocalString  = strAddress.split(/["][^"]*["]/); //matching quotes required
			arrQuotedString = strAddress.match(/["][^"]*["]/g);
		}
	else //No quoted strings
			arrLocalString[0] = strAddress;
		
	for ( la = 0; la < arrLocalString.length && arrLocalString[la]; la++)
		{
			if (arrLocalString[la].match(localPatternCheck) == null || arrLocalString[la].match(/\.{2,}/) != null )
	  		return false;
		}
		
		for ( qa = 0; qa < arrQuotedString.length && arrQuotedString[qa]; qa++)
		{
		if ( arrQuotedString[qa].match(quotePatternCheck) == null )
	  	return false;
		}
		
	return true;
}

function checkDomain(strAddress)
{
	//IP address check uses IPv4 (4 byte) address definition.
	
  var localPattern   = /^([A-Za-z0-9][A-Za-z0-9]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+)$/;
  var localPatternIP = /^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/;

	var arrAddressString     = new Array();
	var temparrAddressString = new Array();
	
  //Check domain portion
	//Must be 1 to 255 characters
	if ( !lengthCheck(strAddress,1,255) )
	  return false;
		
  arrAddressString = strAddress.split(".");

	//Check length
	if ( arrAddressString.length < 2 )
		return false; //Need at least two parts
			
	if ( arrAddressString.length == 4 ) //May be an IPv4 IP address
	{
		//Store arrAddressString in a temp variable
		var temparrAddressString = arrAddressString;
		//Initialize IPAddress flag
		var IPAddress = true;
		
		//Strip off any leading and trailing brackets
		temparrAddressString[0] = temparrAddressString[0].replace(/^\[/, "");
		temparrAddressString[3] = temparrAddressString[3].replace(/\]$/, "");
		
		for ( i = 0; i < 4; i++)
		{
			if ( (temparrAddressString[i].match(localPatternIP) == null) )
			{	//Not an IP address
				IPAddress = false;
				break;
			}
		}
		if ( IPAddress ) 
			return true;
	}
	//Not an IP address, continue validating domain part
	for ( i = 0; i < arrAddressString.length; i++)
	{
		//A portion can be between 1 and 63 characters
		if ( !lengthCheck(arrAddressString[i],1,63) )
			return false;
		
		if ( arrAddressString[i].match(localPattern) == null )
			return false;
	}
	return true;
}

function emailValidator(strAddress)
{
	//Roughly follows RFC5321 (sections 3.2.2 - 3.2.5, 3.4.1) and RFC5322 e-mail guidelines.
	
  var arrEmailAddress = new Array;
			
  // E-mail addresses with control characters are not allowed
  controlKeys = /[\x00-\x1F\x7F-\xFF]/;
	  
  if ( strAddress.match(controlKeys) != null )
  	return false;

	//Remove any leading or trailing whitespaces
	strAddress = strAddress.replace(/^\s+|\s+$/g,"")
	
  //Split into local-name and domain name parts using the last "@"
  //First, check if address contains an "@"
	lastAtPos = strAddress.lastIndexOf("@");
  if ( lastAtPos == -1 )
    return false;		
	
  //Break address into local and domain parts
	arrEmailAddress[0] = strAddress.substr(0,lastAtPos);
	arrEmailAddress[1] = strAddress.substr(lastAtPos + 1);
	
	//Check for "@" symbols in local part not enclosed in quotes. 
	//Only one is allowed.
	 
	//First place the local part in a temparary variable and remove 
	//anything enclosed in quotes.
	arrTempLocalPart = arrEmailAddress[0].replace(/"[^"]+"/g, "");
	 
	//Now check for additional "@" symbols
  if ( arrTempLocalPart.search(/@/) != -1 )
	   return false;

	//Check local portion for validity
	
  if ( !checkLocalPortion( arrEmailAddress[0]) )
	  return false;
		
	//Check domain
	if (!checkDomain(arrEmailAddress[1]) )
	  return false;		 
		
	//All check have passed, return true
	return true;
  
}

function checkEmail(docForm)
{
	var f = docForm;
	var email = f.email.value;
	
	if ( emailValidator(email) )
	{
		document.getElementById("invalidEMail").style.visibility = "hidden";
		document.getElementById("validEMail").style.visibility = "visible";
		//Pause to allow user to read sent message
		wait(7);
		return true;
	}
	else
	{ //Turn user's email to red
		f.email.className = "invalidEMField";
		document.getElementById("invalidEMail").style.visibility = "visible";
		document.getElementById("validEMail").style.visibility = "hidden";
		return false;	
	}
}
