//Macromedia built-in functions

function MM_swapImgRestore()
{ //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages()
{ //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d)
{ //v4.01
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage()
{ //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/* mcc functions */

//update the search form to submit request o a local results page, if javascript is enabled
//otherwise it submits to a Google results page
function updateSearch()
{
	if(document.searchForm)
	{
		document.searchForm.action="/support/search/";
		if(document.searchForm.siteURL)
		{
			document.searchForm.action=document.searchForm.siteURL.value+"/support/search/";
		}
		document.searchForm.cof.value="FORID:11";
	}
}

//deprecated, replaced by the popupWindow function (below)
function newwindow(url, name)
{
	popupWin = window.open(url, name, "width=450,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes");
}

function popupWindow(url, windowname)
{
	/* function used to create a popup window
	url can be a url string, or an anchor object with an href attribute
	windowname can be anything (containing only letters and underscore characters),
	every popup window should have a unique name; more than one link can target 
	the same popup by using the same unique popup name.
	a time.
	
	http://www.htmlcodetutorial.com/linking/linking_famsupp_70.html
	*/
	
	var href;
	var popupWin;
	
	//check for existence of window.focus method
	if(!window.focus)
		//if it doesn't exist, exit script, and open link in current window
		return true;
	
	//get the url from the url object
	if(typeof(url)=='string')
		href=url;
	else
		href=url.href;
	
	//open the popup window
	popupWin=window.open(href, windowname, "width=450,height=550,toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes");
	//set focus to popup window, in case it was in the background
	popupWin.focus();
	//cancel the click on the link, so link isn't opened in current window
	return false;
}

//return a style class object
function getStyleClass(strClassName)
{
	//declare variables
	var returnValue=null;
	
	try
	{
		if(document.styleSheets)
		{
			for(var s=0;s<document.styleSheets.length;s++)
			{
				if(document.styleSheets[s].rules)
				{
					//IE
					for(var r=0;r<document.styleSheets[s].rules.length;r++)
					{
						if (document.styleSheets[s].rules[r].selectorText == '.' + strClassName)
						{
							returnValue=document.styleSheets[s].rules[r];
						}
					}
				}
				else if(document.styleSheets[s].cssRules)
				{
					//regular browsers
					for(var r=0;r<document.styleSheets[s].cssRules.length;r++)
					{
						if (document.styleSheets[s].cssRules[r].selectorText == '.' + strClassName)
							returnValue=document.styleSheets[s].cssRules[r];
					}
				}
			}
		}
	}
	catch(err)
	{
		//do nothing
	}
	
	return returnValue;
}

//highlights an object by changing its class (appends "Highlight" to the class name)
function highlight(obj)
{
	//declare variables
	var append="Highlight"; /* string to append to class name to highlight the object */
	var className=obj.className;
	
	/* check if class name is greater than the append string */
	if(className.length>=append.length)
	{
		/* check if end of class name is already equal to append string */
		if(className.substr(className.length-append.length,append.length)==append)
		{
			//do nothing
		}
		else
		{
			/* append string to class name to highlight object */
			className=className+append;
		}
	}
	else
	{
		/* append string to class name to highlight object */
		className=className+append;
	}
	
	/* apply new class name to object */
	obj.className=className;
}

//unhighlights an object by changing its class (removes "Highlight" from the class name)
function unhighlight(obj)
{
	//declare variables
	var append="Highlight";
	var className=obj.className;
	var pos=0;
	
	pos=className.indexOf(append);
	if(pos>=0)
	{
		className=className.substring(0,pos);
	}
	
	obj.className=className;
}

//randomizes an image by changing its src value
function randomizeImage()
{
	//declare variables
	var imageArray=new Array; //1st passed argument
	var imageObject; //2nd passed argument
	
	//get argument values
	if(arguments[0])
	{
		imageArray=arguments[0];
	}
	if(arguments[1])
	{
		imageObject=arguments[1];
	}
	
	var randomNumber = Math.floor(Math.random()*(imageArray.length))
	imageObject.src = imageArray[randomNumber]
}

//prevents mailto: links from being written explicitly
function mailTo()
{
	//declare variables
	var prefix=""; //1st passed argument
	var domain=""; //2nd passed argument
	var extra=""; //3rd passed argument
	var atsign="&#64;";
	var addr="";
	
	//get argument values
	if(arguments[0])
	{
		prefix=arguments[0];
	}
	if(arguments[1])
	{
		domain=arguments[1];
	}
	if(arguments[2])
	{
		extra=arguments[2];
	}

	addr=prefix+atsign+domain;
	//include 'class="email"' for use in hCard microformat
	document.write("<" + "a" + " class=\"email\" " + "href=" + "\"mail" + "to:" + addr + extra + "\">" + addr + "<\/a>");
}

//creates text in a mailto tag for an email address, but can display alternate text
function mailtoHidden(username, domain, displayText)
{
	var atsign = "&#64;";
	var addr = username + atsign + domain;
	document.write('<' + 'a' + ' ' + 'href="' + 'mail' + 'to:' + addr + '">' + displayText + '<\/a>');
}

//another way of preventing mailto: links from being written explicitly
function mailToOpeningAnchor()
{
	//declare variables
	var prefix=""; //1st passed argument
	var domain=""; //2nd passed argument
	var extra=""; //3rd passed argument
	var atsign="&#64;";
	var addr="";
	
	//get argument values
	if(arguments[0])
	{
		prefix=arguments[0];
	}
	if(arguments[1])
	{
		domain=arguments[1];
	}
	if(arguments[2])
	{
		extra=arguments[2];
	}

	addr=prefix+atsign+domain;
	document.write("<" + "a" + " " + "href=" + "\"mail" + "to:" + addr + extra + "\">");
}

//another way of preventing mailto: links from being written explicitly
function emailAddress(prefix, domain)
{
	//declare variables
	var atsign="&#64;";
	var addr="";
	
	addr=prefix+atsign+domain;
	document.write(addr);
}

//sets a cookie value
function setCookie(strName, strValue, dtmExpires, strPath, strDomain, blnSecure)
{
    document.cookie= strName + "=" + escape(strValue) +
        ((dtmExpires) ? "; expires=" + dtmExpires.toGMTString() : "") +
        ((strPath) ? "; path=" + strPath : "") +
        ((strDomain) ? "; domain=" + strDomain : "") +
        ((blnSecure) ? "; secure" : "");
}

//gets a cookie value
function getCookie(strName)
{
	//declare variables
	var strSearch = strName + "=";
	var strCookie="";
	var intOffset=0;
	var intEnd=0;
	
	if (document.cookie.length > 0)
	{ // if there are any cookies
		intOffset = document.cookie.indexOf(strSearch);
		if (intOffset != -1) // if cookie name exists
		{
			intOffset += strSearch.length // set index of beginning of value
			intEnd = document.cookie.indexOf(";", intOffset); // set index of end of cookie value
			if (intEnd == -1)
			{
				intEnd = document.cookie.length;
			}
			strCookie=unescape(document.cookie.substring(intOffset, intEnd));
		}           
	}
	
	//for browsers that return "undefined" when a cookie is not found, return an empty string instead, for consistent return values across browsers
	if(strCookie=="undefined")
	{
		strCookie="";
	}
	return strCookie;
}

function eraseCookie(strName)
{
	setCookie(strName,"",-1);
}

//checks for a valid email address format
function isValidEmailAddress(email)
{
	//declare variables
	var atPos=email.indexOf("@");
	var dotPos=email.lastIndexOf(".");
	var returnValue=true;
	
	if(email.length==0) //check if email is blank
	{
		returnValue=false;
	}
	else if(atPos<1) //check if there are any characters before the "@" sign
	{
		returnValue=false;
	}
	else if(email.length-dotPos<2) //check if there are any characters after the "."
	{
		returnValue=false;
	}
	else if(dotPos-atPos<2) //check if there are any characters between the "@" and the "." and make sure they're in the right order
	{
		returnValue=false;
	}
	
	return returnValue;
}

function isValidEmailAddress2(email)
{
	//declare variables
	var atPos=email.indexOf("@");
	var dotPos=email.lastIndexOf(".");
	var returnValue=true;
	
	if(email.length==0) //check if email is blank
	{
		returnValue=false;
	}
	else if(atPos<1) //check if there are any characters before the "@" sign
	{
		returnValue=false;
	}
	else if(email.length-dotPos<2) //check if there are any characters after the "."
	{
		returnValue=false;
	}
	else if(dotPos-atPos<2) //check if there are any characters between the "@" and the "." and make sure they're in the right order
	{
		returnValue=false;
	}
	
	
}


//checks for a valid postal/zip code format
function isValidPostalZipCode(postalCode,countryName)
{
	var returnValue=true;
	
	//validate specific content
	if(postalCode.length>0)
	{
		//verify postal code
		if(countryName=="Canada")
		{
			//ensure it is long enough
			if(postalCode.length<6)
			{
				returnValue=false;
			}
			//check for valid format
			else
			{
				var j=0;
				
				// Check for legal characters in string - note index starts at zero
				if('ABCEGHJKLMNPRSTVXY'.indexOf(postalCode.charAt(j)) < 0)
				{
					returnValue=false;
				}
				j++;
				if('0123456789'.indexOf(postalCode.charAt(j)) < 0)
				{
					returnValue=false;
				}
				j++;
				if('ABCEGHJKLMNPRSTVWXYZ'.indexOf(postalCode.charAt(j)) < 0)
				{
					returnValue=false;
				}
				j++;
				
				if(postalCode.charAt(j)==' ')
				{
					j++;
				}
				
				if('0123456789'.indexOf(postalCode.charAt(j)) < 0)
				{
					returnValue=false;
				}
				j++;
				if('ABCEGHJKLMNPRSTVWXYZ'.indexOf(postalCode.charAt(j)) < 0)
				{
					returnValue=false;
				}
				j++;
				if('0123456789'.indexOf(postalCode.charAt(j)) < 0)
				{
					returnValue=false;
				}
			}
		}
		//verify zip code
		else if(countryName=="United States")
		{
			//ensure it is long enough
			if(postalCode.length<5)
			{
				returnValue=false;
			}
			//check for valid format
			else
			{
				//check to make sure each character is numeric (or a space or hyphen)
				for(var i=0;i<postalCode.length;i++)
				{
					if('0123456789 -'.indexOf(postalCode.charAt(i)) < 0)
					{
						returnValue=false;
					}
				}
			}
		}
	}
	else
	{
		returnValue=false;
	}
	
	return returnValue;
}

//format an integer with leading zeros to a specified number of digits
function formatNumber(intValue, intDigits)
{
	var i=0;
	var strString="";

	//fill leading zeros
	for(i=0;i<(intDigits-intValue.toString().length);i++)
	{
		strString+="0";
	}
	//append value as string
	strString+=intValue.toString();

	return strString;
}

function formatCurrency(intAmount)
{
	var strAmount="";
	var strDollars="";
	var strCents="";
	
	if(isNaN(intAmount))
	{
		intAmount=0;
	}
	
	strDollars=Math.floor(intAmount).toString();
	strCents=formatNumber(Math.round(intAmount*100)-Math.floor(intAmount)*100,2);
	strAmount="$"+strDollars+"."+strCents;
	
	return strAmount;
}

function contactTechnicalSubmit(frm)
{
	//submit form
	frm.submit();
	
	/*return false to cancel the click on the link (submitting the form opens the
	desired page if javascript is enabled)*/
	return false;
}

function contactContentSubmit(frm)
{
	//submit form
	frm.submit();
	
	/*return false to cancel the click on the link (submitting the form opens the
	desired page if javascript is enabled)*/
	return false;
}

//checks a URL by opening it in a new window (used on "Contact the Web Editor" form)
function checkURL(textfield)
{
	window.open(textfield.value);
}

function disableSubmit(frm,returnValue)
{
	//disable submit button if returnValue is true
	//to prevent people from submitting twice if the server 
	//response is slow in bringing up the next page.
	if(returnValue==true)
	{
		//insert "please wait" message
		document.getElementById("pleaseWait").style.display="inline";
		
		//disable submit button
		frm.submit.disabled=true;
	}
}

/* ajax functions */

function createRequest()
{
	//declare variables
	var returnValue=null;
	
	try
	{
		returnValue = new XMLHttpRequest();
	}
	catch(microsoftOption1)
	{
		try
		{
			returnValue = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(microsoftOption2)
		{
			try
			{
				returnValue = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(failed)
			{
				returnValue=null;
			}
		}
	}
	
	return returnValue;
}

/* fade functions */

//declare global variables
var objFadeIn=null;
var objFadeOut=null;
var objTimeoutFadeIn=null;
var objTimeoutFadeOut=null;

function fadeIn(obj)
{
	//declare variables
	var intFadeTime=0; //second parameter - time in milliseconds
	var intFadeIncrement=0 //third parameter - fade increment percentage
	var intFadeStep=0 //fourth parameter - current fade step
	
	//check for second passed parameter
	if(!arguments[1])
	{
		intFadeTime=1000; //set default fade time to 1 second
	}
	else
	{
		intFadeTime=arguments[1];
	}
	
	//check for third passed parameter
	if(!arguments[2])
	{
		intFadeIncrement=10; //set default fade increment
	}
	else
	{
		intFadeIncrement=arguments[2];
	}
	
	//check for third passed parameter
	if(!arguments[3])
	{
		intFadeStep=0; //set current fade step to 0
	}
	else
	{
		intFadeStep=arguments[3]; //increment passed fade step
	}
	
	objFadeIn=obj;
	
	//check if object has not completed fade in
	if((intFadeIncrement*intFadeStep)<100)
	{
		//increment fade step
		intFadeStep++;
		
		//fade in object
		setOpacity(objFadeIn,(intFadeIncrement*intFadeStep));
		
		//call function recursively, with timeout
		objTimeoutFadeIn=setTimeout("fadeIn(objFadeIn,"+intFadeTime+","+intFadeIncrement+","+intFadeStep+");",intFadeTime/(100/intFadeIncrement));
	}

	//return timeout obj so fadeIn can be cancelled
	return objTimeoutFadeIn;
}

function fadeOut(obj)
{
	//declare variables
	var intFadeTime=0; //second parameter - time in milliseconds
	var intFadeIncrement=0 //third parameter - fade increment percentage
	var intFadeStep=0 //fourth parameter - current fade step

	//check for second passed parameter
	if(!arguments[1])
	{
		intFadeTime=1000; //set default fade time to 1 second
	}
	else
	{
		intFadeTime=arguments[1];
	}

	//check for third passed parameter
	if(!arguments[2])
	{
		intFadeIncrement=10; //set default fade increment
	}
	else
	{
		intFadeIncrement=arguments[2];
	}
	
	//check for third passed parameter
	if(!arguments[3])
	{
		intFadeStep=0; //set current fade step to 0
	}
	else
	{
		intFadeStep=arguments[3]; //increment passed fade step
	}

	objFadeOut=obj;
	
	//check if object has not completed fade out
	if(100-(intFadeIncrement*intFadeStep)>0)
	{
		//increment fade step
		intFadeStep++;
		
		//fade out object
		setOpacity(objFadeOut,100-(intFadeIncrement*intFadeStep));
		
		//call function recursively, with timeout
		objTimeoutFadeIn=setTimeout("fadeOut(objFadeOut,"+intFadeTime+","+intFadeIncrement+","+intFadeStep+");",intFadeTime/(100/intFadeIncrement));
	}
	
	//return timeout obj so fadeOut can be cancelled
	return objTimeoutFadeIn;
}

function setOpacity(obj, intOpacity)
{
	//limit passed opacity value to between 0 and 100
	if(intOpacity<0)
	{
		intOpacity=0;
	}
	else if(intOpacity>100)
	{
		intOpacity=100;
	}
	
	//set display
	if(intOpacity>0)
	{
		obj.style.display='block';
	}
	else
	{
		obj.style.display='none';
	}
	
	//set opacity
	//obj.style.filter="alpha(opacity="+intOpacity+")"; //IE deprecated
	obj.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+intOpacity+")"; //IE
	obj.style.MozOpacity=intOpacity/100; //Mozilla/Netscape
	obj.style.opacity=intOpacity/100; //Opera + W3C standard
	
	if(intOpacity==100)
	{
		if(isSafari())
		{
			obj.style.opacity=.9999; /* objects in Safari disappear at 100 opacity (for some unknown reason) */
		}
	}
}

//check if browser is Safari
function isSafari()
{
	//declare variables
	var returnValue=false;
	
	if(navigator.vendor)
	{
		if(navigator.vendor.indexOf("Apple") != -1)
		{
			returnValue=true;
		}
	}
	
	return returnValue;
}

/* survey functions */

//declare global variables
var objRequest=null;
var strStatusCookieName="MCCSurveyStatus";
var strSurveyCloseCountCookieName="MCCSurveyClosedCount";
var intCloseLimit=3; //how many times a user has to close the survey before it will not be displayed again
var intCookieExpireDays=31; //how many days before survey cookies expire
var intDisplayDelay=1500; //delay before displaying survey on a page, milliseconds
var strSurveyPath="/";
//var strSurveyDomain="mcc.org"; //not used, prevents survey from working properly on mennonitecc.ca domain

function survey1()
{
	//check if this function has been called with a parameter
	if(!arguments[0])
	{
		//called with no paramter
		//write initial html
		document.write("<div class=\"surveyContainer\" id=\"survey1\"></div>");
		
		//call this function recursively, with a delay, and passing a paramter of "1"
		setTimeout("survey1(1);",intDisplayDelay);
	}
	else if(arguments[0]==1)
	{
		//called with paramter of "1"
		//check if survey should be displayed
		if(blnDisplaySurvey())
		{
			//display survey
			objRequest=createRequest();
			objRequest.open("GET","/include/surveys/survey1.html",true);
			objRequest.onreadystatechange=survey1Display;
			objRequest.send(null);
		}
	}
}

function survey1Display()
{
	if(objRequest.readyState==4)
	{
		if(objRequest.status==200)
		{
			//display survey content
			document.getElementById("survey1").innerHTML=objRequest.responseText;
			
			//display survey
			fadeIn(document.getElementById("survey1"),500);
		}
		else
		{
			alert("There was a problem with a request on the page.\nStatus Code: "+objRequest.status);
		}
	}
}

function survey1ThankYou()
{
	if(objRequest.readyState==4)
	{
		if(objRequest.status==200)
		{
			//display thank you message
			document.getElementById("survey1").innerHTML=objRequest.responseText;
			
			//close the survey
			setTimeout("fadeOut(document.getElementById(\"survey1\"));",800);
		}
		else
		{
			//close the survey anyway
			fadeOut(document.getElementById("survey1"));
		}
	}
}

function survey1CloseClick()
{
	//declare variables
	var intClosedSurveyCount=0;
	
	//close the survey
	document.getElementById("survey1").style.display="none";

	//get and increment closed survey count
	intClosedSurveyCount=parseInt(getCookie(strSurveyCloseCountCookieName),10)+1;
	//set closed survey count cookie
	setCookie(strSurveyCloseCountCookieName,intClosedSurveyCount,getExpiryDate(),strSurveyPath);
	
	//check if status should be changed
	if(intClosedSurveyCount >= intCloseLimit)
	{
		//set status cookie
		setCookie(strStatusCookieName,"2",getExpiryDate(),strSurveyPath);
	}
	
	//increment count in database
	objRequest=createRequest();
	objRequest.open("GET","/include/surveys/survey1Closed.php?type=0",true);
	objRequest.onreadystatechange=dummy;
	objRequest.send(null);
	
	//cancel link
	return false;
}

function survey1ClosePermanent()
{
	//close the survey
	document.getElementById("survey1").style.display="none";
	//set status cookie
	setCookie(strStatusCookieName,"3",getExpiryDate(),strSurveyPath);
	
	//increment count in database
	objRequest=createRequest();
	objRequest.open("GET","/include/surveys/survey1Closed.php?type=1",true);
	objRequest.onreadystatechange=dummy;
	objRequest.send(null);
	
	//cancel link
	return false;
}

function survey1Submit(frm)
{
	//declare variables
	var returnValue=true;
	
	//check for valid inputs
	if(frm.age.value=="")
	{
		survey1Alert("Please select your age category");
		frm.age.focus();
		returnValue=false;
	}
	else if(frm.gender.value=="")
	{
		survey1Alert("Please select your gender");
		frm.gender.focus();
		returnValue=false;
	}
	
	if(returnValue)
	{
		//disable submit button
		disableSubmit(frm,returnValue);
		
		//set status cookie
		setCookie(strStatusCookieName,4,getExpiryDate(),strSurveyPath);
		
		//submit survey results
		objRequest=createRequest();
		objRequest.open("GET","/include/surveys/survey1Submit.php"+"?age="+frm.age.value+"&gender="+frm.gender.value,true);
		objRequest.onreadystatechange=survey1ThankYou;
		objRequest.send(null);
	}
	
	//cancel form submit
	return false;
}

function survey1Alert(strAlertText)
{
	document.getElementById("survey1Alert").innerHTML=strAlertText;
}

function blnDisplaySurvey()
{
	//cookie status key
	// 1 - survey has been displayed, but has not yet received a response
	// 2 - survey has been closed by user enough times that it will not be displayed again
	// 3 - user does not want to see survey again
	// 4 - survey has already been completed
	
	//declare variables
	var returnValue=true;
	var intStatus=0;
	
	//get survey status
	intStatus=getCookie(strStatusCookieName);
	
	switch(true)
	{
		case(intStatus==1):
			//display the survey
			returnValue=true;
			break;
		case(intStatus==2):
			//do not display survey
			returnValue=false;
			break;
		case(intStatus==3):
			//do not display survey
			returnValue=false
			break;
		case(intStatus==4):
			//do not display survey
			returnValue=false
			break;
		default:
			//this check has not been run before
			//set status cookie
			setCookie(strStatusCookieName,1,getExpiryDate(),strSurveyPath);
			//set closed survey count cookie
			setCookie(strSurveyCloseCountCookieName,0,getExpiryDate(),strSurveyPath);
	
			//display the survey
			returnValue=true;
	}
	
	return returnValue;
}

function getExpiryDate()
{
	//declare variables
	var dtmDate=new Date();
	dtmDate.setDate(dtmDate.getDate()+intCookieExpireDays);
	
	return dtmDate;
}

function dummy()
{
}

//DHTML display options
function getObj(name)	
{
	if (document.getElementById)	
	{   // DOM level 1 browsers: IE 5+, NN 6+
		this.obj = document.getElementById(name);
		this.style = document.getElementById(name).style;
 	}
  	else if (document.all)	
	{ 	// IE 4
		this.obj = document.all[name];
		this.style = document.all[name].style;
	}
	else if (document.layers)  
	{ 	// NN 4
	   	this.obj = document.layers[name];
	   	this.style = document.layers[name];
	}
}

//makes object visible
function display(visible) 
{
	var displayObject = new getObj(visible);
	displayObject.style.display = 'block';
}
	
//makes object invisible	
function hide(invisible) 
{
	var hiddenObject = new getObj(invisible);
	hiddenObject.style.display = 'none';
}	
