// Commonly used Javascript functions used by BJU 6 pages.

// Functions to handle events responsibly
// Written by Dean Edwards, 2005, http://dean.edwards.name/weblog/2005/10/add-event/
// Modified by Scott Buchanan, Apr 08
function addEvent(element, type, handler) {
	if (!handler.$$guid) handler.$$guid = addEvent.guid++;
	if (!element.myevents) element.myevents = {};
	var handlers = element.myevents[type];
	if (!handlers) {
		handlers = element.myevents[type] = {};
		if (element["on" + type]) {
			handlers[0] = element["on" + type];
		}
	}
	handlers[handler.$$guid] = handler;
	element["on" + type] = handleEvent;
};
addEvent.guid = 1;
function removeEvent(element, type, handler) {
	if (element.myevents && element.myevents[type]) {
		delete element.myevents[type][handler.$$guid];
	}
};
function handleEvent(event) {
	var returnValue = true;
	event = event || fixEvent(window.event);
	var handlers = this.myevents[event.type];
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};
fixEvent = function (event) {
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};

// Function to recursively remove all empty text nodes and comments from DOM tree.
// Derived from removeEmptyTextNodes in MochiKit dev release 1323
// Modified by Scott Buchanan, Jan-Feb 08
function cleanDOMTree (element) {
	// Iterate through each child of the element.
	for (var i = 0; i < element.childNodes.length; ++i) {
		var myNode = element.childNodes[i];
		// If the child is a comment or an empty text node, remove it.
		if (myNode.nodeType == 8 || (myNode.nodeType == 3 && !/\S/.test(myNode.nodeValue))) {
			myNode.parentNode.removeChild (myNode);
			--i;
		// If the child is an element with children, recurse into it.
		} else if (myNode.nodeType == 1 && myNode.childNodes.length) {
			cleanDOMTree (myNode);
		}
	}
}

// Functions to do AJAX requests.
// By Scott Buchanan, Apr 08
function createAjaxObject () {
	var http;
	if (window.xmlHTTP) {
		http = window.xmlHTTP.http;
	} else {
		if (typeof XMLHttpRequest != 'undefined') http = new XMLHttpRequest();
		if (! http) try { http = new ActiveXObject('Msxml2.xmlHTTP'); } catch (e) {}
		if (! http) try { http = new ActiveXObject('Microsoft.xmlHTTP'); } catch (e) {}
		if (! http) return false;
		window.xmlHTTP = {};
		window.xmlHTTP.http = http;
	}
	
	xmlHTTP.sendRequestXML = function (url, success, failure) {
		xmlHTTP.successCallback = (success == null) ? function () {} : success;
		xmlHTTP.failureCallback = (failure == null) ? function () {} : failure;
		try {
			http.open ('GET', url);
			http.setRequestHeader ('Content-Type', "text/xml");
			http.onreadystatechange = xmlHTTP.handleResponseXML;
			http.send (null);
		} catch (e) {
			if (window.console && window.console.error) console.error (e);
			return false;
		}
		return true;
	}
	
	xmlHTTP.handleResponseXML = function (url) {
		try {
			if (http.readyState == 4) {
				if (http.status == 200) {
					xmlHTTP.successCallback (http.responseXML.documentElement);
				} else {
					xmlHTTP.failureCallback ();
				}
			}
		} catch (e) { if (window.console && window.console.error) console.error (e); }
	}
	
	return true;
}

// Function to set up home page specific navigation menus
// Written by Scott Buchanan, Jan/Feb 08
function createHomeMenus() {
	// Get the list of main menu categories, clean the DOM tree, and set up menus iteratively.
	var cats = document.getElementById('categories');
	cleanDOMTree (cats);
	for (var i = 0; i < cats.childNodes.length; ++i) {
		var cat = cats.childNodes[i];
		
		// Since there are some items that are not categories, skip them.
		if (cat.className != 'category') continue;
		
		// Create anonymous function handlers for category rollovers.
		cat.onmouseover = function () {
			this.lastChild.style.display = 'block';
			this.firstChild.firstChild.src = 'images/categories/' + this.firstChild.firstChild.id + '_over.jpg';
		}
		cat.onmouseout = function () {
			this.lastChild.style.display = 'none';
			this.firstChild.firstChild.src = 'images/categories/' + this.firstChild.firstChild.id + '.jpg';
		}
	}
	
	// Call function to create standard menus.
	createMenus();
}

// Function to set up site-wide navigation menus
// Written by Scott Buchanan, Mar 08
function createMenus() {
	// Set up additional ministries menu.
	var menulink = document.getElementById('ministrieslink');
	menulink.onmouseover = function () { document.getElementById('ministrypopup').style.display = 'block'; }
	menulink.onmouseout	 = function () { document.getElementById('ministrypopup').style.display = 'none'; }
}

// Functions to handle cookies on the client-side
// Written by Scott Andrew and Peter-Paul Koch, http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}

// Function to display a given element as an overlaid popup.
function overlayPopup(popID, createPopElem) {
	// Create background overlay if necessary.
	var overlay = document.getElementById('popupOverlay');
	if (! overlay) {
		overlay = document.createElement('div');
		overlay.id = 'popupOverlay';
		document.body.appendChild (overlay);
	}
	
	// Create pop-up if necessary;
	var popup = document.getElementById(popID);
	if (! popup) {
		popup = document.createElement('div');
		popup.id = popID;
		popup.className = 'overlayPopup';
		popup.appendChild(createPopElem());
		document.body.appendChild (popup);
	}
	
	// Display popup.
	overlay.style.display = 'block';
	popup.style.display = 'block';
	
	return popup;
}
function closeOverlayPopup(popID) {
	document.getElementById('popupOverlay').style.display = 'none';
	document.getElementById(popID).style.display = 'none';
}

// Function to overlay an email form to send a gallery picture to a friend.
// Called using ExternalInterface from within the Flash file.
function popupGalleryEmailForm(xmlURI, photoIndex) {
	// Convert relative XML path to absolute.
	if (xmlURI.charAt(0) != '/') {
		xmlURI = location.pathname.replace(/\/[^\/]*$/, '/') + xmlURI;
	}
	
	// Create popup proper.
	var popup = overlayPopup('galleryEmailPopup', function () {
		return document.createElement('iframe');
	});
	
	// Set URL for inline frame in popup.
	var formURI = window.location.protocol + '//';
	formURI += window.location.host;
	formURI += '/galleries/email.php?xml=' + escape(xmlURI) + '&photo=' + photoIndex;
	popup.lastChild.src = formURI;
}

// Function to obfuscate email addresses at BJU.
// Gabriel Feindel
// A safe, simple way of emailing that confounds even the brightest email harvester.
// To use in an email link, set href to "#" and onclick to mailto("username") where
// username is the part before the @ sign in the email address. Only works with 
// users on bju.edu
function mailto(uname, domain) {
	if (domain == undefined) domain = 'bju.edu';
	var address = uname + "@" + domain;
	if (pageTracker) pageTracker._trackEvent('mailto', 'click', address);
	window.location.href = "mailto:" + uname + "@" + domain;
}

// Function used to hide/show div tag elements. Pass in the ID of the div to hide/show (divID) along with the element that 
// is controlling the hide/show toggle (thisobj). If the div is hidden, it will be displayed, if it is displayed it will be hidden. 
function unhide(divID, thisobj) {
	var elem = document.getElementById(divID);
	if (elem) {
		if (elem.className == 'hidden') {
			elem.className = 'unhidden';
			thisobj.className = 'answer';
		} else {	
			elem.className = 'hidden';
			thisobj.className = 'question';
		}	
	}
}

// Switch code allows for multiple div's to be switched between
function change_section(section) {
	x = document.getElementById(section);
	dest = document.getElementById('rotate');
	dest.innerHTML = x.innerHTML;
	return false;
}

// form validation
// by Matt Slocum
// requires: <script type="text/javascript"> fields = new Array("required_field1", "required_field2"); </script>
// <form ... onsubmit="return validateForm(this);">
function validateForm(f) {
	if (fields == undefined) { return true; }
	var good = true;
	for(i = 0; i < fields.length; i++) {
		if ( !validField(eval("f." + fields[i])) ) {
			if (good) { alert("You did not fill in all the required fields!"); }
			if (eval("f." + fields[i]).type != undefined) {
				if (good) { eval("f." + fields[i]).focus(); }
				eval("f." + fields[i]).style.background = "lightyellow";
			}
			
			if ((eval("f." + fields[i])[0] != undefined) && (eval("f." + fields[i])[0].parentNode.tagName == "TD")) 
				eval("f." + fields[i])[0].parentNode.style.background = "lightyellow"; 
				
			if (eval("f." + fields[i]).type == "checkbox")
				eval("f." + fields[i]).parentNode.style.background = "lightyellow"; 
				
			good = false;
		}
	}
	return good;
}
	
function validField(field) {
	if (field.type == "checkbox") {
		if (!field.checked) {
			return false;
		}
	}
	switch (field.value) {
		case "":
			return false;
			break;
		case " ":
			return false;
			break;
		case undefined:
			if (field[0].type == "radio") {
				for (n = 0; n < field.length; n++) {
					if (field[n].checked) {
						return true;
					}
				}
				return false;
			}
			break;
		default:
			return true;
			break;
	}
	return true;
}

// Added by JRH to support building list menu under Campus Map
function MM_jumpMenu(targ,selObj,restore){ //v3.0
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	if (restore) selObj.selectedIndex=0;
}