initMain = function() {
	// Get root ID of navigation (menu) bar.
	var navRoot = document.getElementById("nav");
	// Add Suckerfish hover class (sfhover) for nav bar <li> elements in IE.
	if (window.attachEvent) {
		var sfElements = navRoot.getElementsByTagName("LI");
		for (var i=0; i<sfElements.length; i++) {
			sfElements[i].onmouseover = function() {this.className += " sfhover";}
			sfElements[i].onmouseout = function() {this.className = this.className.replace(new RegExp(" sfhover\\b"), "");}
		}
		var calRoot = document.getElementById("calendar");
		if (calRoot) {
			var sfElements = calRoot.getElementsByTagName("A");
			for (var i=0; i<sfElements.length; i++) {
				sfElements[i].onmouseover = function() {this.className += " sfhover2";}
				sfElements[i].onmouseout = function() {this.className = this.className.replace(new RegExp(" sfhover2\\b"), "");}
			}
		}
	}

	// Set up a few Regexs for examining the document URLs.
	var overlayRegex1  = /_overlay\./;			// used for modifying overlay links
	var overlayRegex2  = /\?overlay=(\d+)$/;	// used for checking overlay information passed in the URL
	var lastDotRegex   = /(.*)\./;				// locate the final dot in the URL string
	var lastHashRegex  = /#$/;					// identify named ('#') anchors

	if (mobile) defaultOverlay = 0;		// Force default overlay to 0 for mobile devices.
	
	// For non-mobile devices, change "overlay" links to point to non-overlay pages, and
	// deactivate nav bar links to main sub-area (i.e. directory-level "index.php") pages.
	else {
		// Modify nav bar links to point to non-overlay pages.
		var navLinks = navRoot.getElementsByTagName("A");
		for (var i=0; i<navLinks.length; i++) {
			navLinks[i].href = navLinks[i].href.replace(overlayRegex1,'.');
		}

		// Modify main text links to point to non-overlay pages.
		var mainText = document.getElementById("mainText");
		if (mainText) {
			var mainLinks = mainText.getElementsByTagName("A");
			for (var i=0; i<mainLinks.length; i++) {
				mainLinks[i].href = mainLinks[i].href.replace(overlayRegex1,'.');
			}
		}

		// Modify nav bar links to point to '#' rather than intermediate pages.
		for (var i=0; i<navRoot.childNodes.length; i++) {
			var node = navRoot.childNodes[i];
			if (node.nodeName == "LI") {
				for (var j=0; j<node.childNodes.length; j++) {
					var nodeChild = node.childNodes[j];
					if (nodeChild.nodeName == "A") nodeChild.href = "#";
				}
			}
		}

		// Add onclick and onkeypress functions to all links ending with "#" to "deactivate" them.
		var docLinks = document.getElementsByTagName("A");
		for (var i=0; i<docLinks.length; i++) {
			var node = docLinks[i];
			if (node.href.match(lastHashRegex)) {
				node.onclick = function() {return(false);}
				node.onkeypress = function() {return(false);}
				node.style.cursor = "default";
			}
		}

		// Pre-load "loading" image and background photos for all (non-mobile) pages.
		var loadingImg = new Image(); loadingImg.src = '/images/loading.gif'
		var bkgImage0 = new Image(); bkgImage0.src = '/images/home.jpg';
		var bkgImage1 = new Image(); bkgImage1.src = '/images/about.jpg';
		var bkgImage2 = new Image(); bkgImage2.src = '/images/ministries.jpg';
		var bkgImage3 = new Image(); bkgImage3.src = '/images/churchlife.jpg';
		var bkgImage4 = new Image(); bkgImage4.src = '/images/resources.jpg';
		var bkgImageOverlay1 = new Image(); bkgImageOverlay1.src = '/images/about_overlay.jpg';
		var bkgImageOverlay2 = new Image(); bkgImageOverlay2.src = '/images/ministries_overlay.jpg';
		var bkgImageOverlay3 = new Image(); bkgImageOverlay3.src = '/images/churchlife_overlay.jpg';
		var bkgImageOverlay4 = new Image(); bkgImageOverlay4.src = '/images/resources_overlay.jpg';
	}

	// See if this is an "overlay" page.
	var thisDoc = window.location.href;
	var parentDoc = parent.location.href;
	if (parentDoc != thisDoc && thisDoc.search(overlayRegex1) > 0) {
		// See if this overlay page is being displayed in an iframe, not as a standalone page.
		var parentDocIndex = parentDoc.search(overlayRegex2);
		if (parentDocIndex > 0) parentDoc = parentDoc.substr(0,parentDocIndex);
		var regexResults = lastDotRegex.exec(parentDoc)
		if (regexResults) parentDoc = regexResults[1];
		if (parentDoc == thisDoc.substr(0,parentDoc.length)) {
			// Do not display header ("main") area.
			document.getElementById("main").style.display = "none";
			// Add 50 pixels to top of overlay display ('overlayPage') area.
			document.getElementById("overlayPage").style.paddingTop = "50px";
			// Check to make sure all images are preloaded before allowing any overlay displays.
			// This function will display the "Loading..." graphic if necessary and set the overlayOK
			// flag to true when done.
			checkImages(0);
		}
		// Otherwise, set overlayOK flag to false so we know not to process overlay links.
		else overlayOK = false;  // Standalone overlay page.
	}

	// If overlay information is passed in the URL, display that overlay.
	var overlayResults = overlayRegex2.exec(window.location.href);
	if (overlayResults) {
		overlayAutoload = true;
		overlay(overlayResults[1]);
	// Otherwise, if a default overlay is enabled in the page, display that overlay.
	} else if (defaultOverlay>0) {
		overlayAutoload = true;
		overlay(defaultOverlay);
	}
}

// Add the initMain function to the onload event handler.
if (window.addEventListener) //DOM method for binding an event.
	window.addEventListener("load", initMain, false);
else if (window.attachEvent) //IE exclusive method for binding an event.
	window.attachEvent("onload", initMain);
else if (document.getElementById) //support for older modern browsers.
	window.onload = initMain;

// Check to make sure all images are preloaded before allowing any overlay displays
var overlayImages = new Array();
var overlayBkgrImage;
function checkImages(iteration) {
	var overlayComplete = true;
	if (iteration == 0) {
		// First time only: set up array of images so we can check their download status.
		// The array will hold all the images defined in the HTML of the overlay page.
		var overlayPg = document.getElementById("overlayPage");
		if (overlayPg) overlayImages = overlayPg.getElementsByTagName("IMG");
		// Now get the overlay page background image.  This is defined in CSS, so we can't just look at the page source.
		var overlayBkgrID = parent.document.getElementById('overlayPhoto');
		if (overlayBkgrID) {
			var overlayBkgrPhoto = null;
			if (parent.document.defaultView && parent.document.defaultView.getComputedStyle) {
				// Use "getComputedStyle" method (DOM2) if available
				var computedStyle = parent.document.defaultView.getComputedStyle(overlayBkgrID,null);
				if (computedStyle && computedStyle.getPropertyValue)
					overlayBkgrPhoto = computedStyle.getPropertyValue('background-image');
			}
			if (!overlayBkgrPhoto && overlayBkgrID.currentStyle)
				// Otherwise use older "currentStyle" property.
				overlayBkgrPhoto = overlayBkgrID.currentStyle['backgroundImage'];
			// Whichever way we get it, strip off the "url" text and parentheses.
			if (overlayBkgrPhoto && overlayBkgrPhoto.match(/^url/)) {
				overlayBkgrImage = new Image();
				overlayBkgrImage.src = overlayBkgrPhoto.replace(/^url|[()"]/g, '');
			}
		}
	}

	// Now, check the status of each image in the array. 
	for (var i=0; i<overlayImages.length; i++) {
		if (!overlayImages[i].complete) {
			overlayComplete = false;
			break;
		}
	}
	// And finally, check the status of the background image.
	if (overlayBkgrImage && !overlayBkgrImage.complete) overlayComplete = false;

	// If everything is downloaded or it's taking too long (more than 8 seconds), set flag so we know it's OK to process overlay links now.
	if (overlayComplete || iteration>40) {
		parent.document.getElementById('loading').style.display = "none";
		parent.overlayOK = true;
	}
	// Otherwise, check again in 200 milliseconds.
	else {
		if (iteration>0 && parent.overlayAutoload) parent.document.getElementById('loading').style.display = "block";
		window.setTimeout("checkImages("+(iteration+1)+")",200);
	}
}

// High-level function to handle overlays.
function overlay(overlayNumber,iteration) {

	// overlayNumber values:
	//	 0: hide all overlays
	//	-1: display all overlays
	//	any other number, display specified overlay, hide everything else
	if (currOverlay == overlayNumber) overlayNumber = 0;

	// See if we are running on a mobile device.
	if (mobile) {
		// Define this page and a few regexes
		var thisDoc = window.location.href;
		var overlayRegex = /_overlay\./;		// used mto locate overlay pages
		var cmdRegex     = /\?overlay=.*/;		// used to clear any overlay parameters
		var phpRegex     = /\.php?/;			// used to insert overlay page modification
		// If we're not on an overlay page, redirect to that page with the appropriate overlay number.
		if (thisDoc.search(overlayRegex)==-1) {
			newDoc = thisDoc.replace(cmdRegex,"");
			newDoc = thisDoc.replace(phpRegex,"_overlay.php");
			if (overlayNumber!=0) newDoc = newDoc + "?overlay=" + overlayNumber;
			window.location=newDoc;
		} else {
			// Otherwise, display requested overlay area(s) (if any) and hide everything else.
			var overlayID;
			for (var i=1; ; i++) {
				overlayID = document.getElementById('overlay'+i);
				if (overlayID == undefined || overlayID == null) break;
				if (i == overlayNumber || overlayNumber == -1) overlayID.style.display = 'block';
				else overlayID.style.display = 'none';
			}
			if (overlayNumber != 0) document.getElementById('overlay'+(overlayNumber==-1?1:overlayNumber)).scrollIntoView();
		}
	// Otherwise, we're running on a non-mobile (desktop) device.
	} else {
		// Set default value of iteration variable.
		if (iteration == undefined || iteration == null) iteration = 0;
	
		// Define frame document. If none exists, see if parent document has a frame and execute this function there.
		var frameDoc = null;
		var frameID = document.getElementById('overlayFrame');
		if (frameID) {
			frameDoc = frameID.contentDocument;
			if (frameDoc == undefined || frameDoc == null) frameDoc = frameID.contentWindow.document;
		} else {
			if (window.location.href != parent.location.href && parent.overlay) return(parent.overlay(overlayNumber,iteration));
			else {
				document.getElementById('overlay'+(overlayNumber==-1?1:overlayNumber)).scrollIntoView();
				return(false);
			}
		}

		// Note: below this point, this function should only execute in the top-level (non-overlay) page.

		// Clear any previous call to setTimout.
		if (overlayTimerID) {
			clearTimeout(overlayTimerID);
			overlayTimerID = 0;
		}
		// See if this is a standalone overlay page (i.e. all overlays are permanently displayed).  If so, bail out.
		if (overlayOK == false) return(true);

		// See if the overlay page has not yet finished hiding the headers and menus we don't want to see.
		if (overlayOK == null) {
			// Set timeout to execute this function again in a 200 milliseconds.
			// if (iteration>0 && overlayAutoload) document.getElementById('loading').style.display = "block";
			overlayTimerID = window.setTimeout("overlay("+overlayNumber+","+(iteration+1)+")",200);
			return(false);
		}
		// if (overlayAutoload) document.getElementById('loading').style.display = "none";

		// Bail out if a fade in or fade out is currently in progress.
		if (fadeInProgress) return(false);

		// Define element to set opacity
		overlayElement = document.getElementById('overlayPhoto');

		if (overlayNumber == 0) {
			// Hide all overlays
			if (currOverlay) fadeOutOverlay(100);
		} else {
			if (currOverlay) {
				// Hide all overlays and set up for displaying the new one.
				newOverlay = overlayNumber;
				transitionTime = 10;
				fadeOutOverlay(100);
				overlayNumber = 0;
			} else {
				// Set up the selected overlay to display and hide everything else
				for (var i=1; ; i++) {
					var overlayID = frameDoc.getElementById('overlay'+i);
					if (overlayID == undefined || overlayID == null) break;
					if (i == overlayNumber || overlayNumber == -1) overlayID.style.display = 'block';
					else overlayID.style.display = 'none';
				}
				if (!currOverlay) fadeInOverlay(0);
			}
		}
	}
	currOverlay = overlayNumber;
	return(false);
}

// Hide all overlays.
function clearOverlay() {
	return(overlay(0,0));
}

// Display all overlays.
function displayAll() {
	return(overlay(-1,0));
}

// Overlay flag to indicate if/when overlays can be procesed.
//	null: page is not yet initialized; try again later.
//	false: no overlay processing allowed
//	true: overlays allowed and available
var overlayOK = null;

// Define current overlay:
// 0=none, -1=all, otherwise it is the number of the currently displayed overlay
var currOverlay = 0;

// Define new overlay, i.e. the one to go to after fading out the current one
var newOverlay = 0;

// Define time (in ms) between calls to window.setTimeout for faded transitions.
// The only time this is shortened is when we're transitioning from one overlay to another.
var transitionTime = 25;

// Flag used to prevent multiple fade ins/outs from trying to happen at the same time
var fadeInProgress = false;

var overlayTimerID = 0;
var overlayElement;
var overlayAutoload = false;

// Set the opacity for the overlay page.
function setOverlayOpacity(opacity) {
	var opacityPct = opacity/100;
	overlayElement.style.opacity = opacityPct;
	overlayElement.style.MozOpacity = opacityPct;
	overlayElement.style.KhtmlOpacity = opacityPct;
	overlayElement.style.filter = "alpha(opacity="+opacity+")";
}

// Fade in an overlay page.
function fadeInOverlay(opacity) {
	opacity += 10;	// Increment opacity percentage.
	if (opacity >= 100) {
		// Full opacity: don't use 100 because it makes the image blink on some browsers.
		setOverlayOpacity(99);
		fadeInProgress = false;
		// Reset transition time for next fade
		transitionTime = 25;
	} else {
		// Set the partial opacity.
		setOverlayOpacity(opacity);
		// First time: display the overlay and set the "in progress" flag.
		if (opacity == 10) {
			overlayElement.style.display = "block";
			fadeInProgress = true;
		}
		// Set timer to come back for the next step.
		window.setTimeout("fadeInOverlay("+opacity+")",transitionTime);
	}
}

// Fade out an overlay page
function fadeOutOverlay(opacity) {
	opacity -= 10;	// Decrement opacity percentage.
	if (opacity <= 0) {
		// Last time: don't bother setting the opacity, just turn off the display.
		overlayElement.style.display = "none";
		fadeInProgress = false;
		if (newOverlay) {
			// Set timer to come back to begin the fade-in.
			window.setTimeout("overlay("+newOverlay+")",transitionTime);
			// Reset the new overlay flag
			newOverlay = 0;
		}
	} else {
		// Set the "in progress flag" and set the partial opacity.
		fadeInProgress = true;
		setOverlayOpacity(opacity);
		// Set timer to come back for the next step.
		window.setTimeout("fadeOutOverlay("+opacity+")",transitionTime);
	}
}
