function initEvents()
{	// initialize the page's event handlers. This is called as an event on window load.
	// first set up the left menu
	if (! document.getElementsByTagName) return;
	// The left menu consists of anchor/img separator line pairs.
	// Give the anchor an id of ml# and the img separator an id of s#
	var lm = findObj('leftmenu');
	var ix = 0;
	for(var i=0; i < lm.childNodes.length; i++) {
		var lnk = lm.childNodes[i];
		if (lnk.nodeName.toLowerCase() == 'a') {
			// found an anchor. Bump ix (the # used in the id's), add the
			// mouseover, mouseout, and focus event handlers, and give it its id.
			ix += 1;
			addEvent(lnk, 'mouseover', lmMouseOver, false);
			addEvent(lnk, 'mouseout', lmMouseOut, false);
			addEvent(lnk, 'focus', gotFocus, false);
			lnk.id = 'ml' + ix;	// give it an id
		} else if (lnk.nodeName.toLowerCase() == 'img') {
			lnk.id = 's' + ix;	// give the img an id with the same number as the anchor
		}
	}
	// now kill the focus box around the top banner
	var tb = findObj('topbanner');
	allLinks = tb.getElementsByTagName('a');
	addEvent(allLinks[0], 'focus', gotFocus, false);
	// if there is a submenu, kill their focus boxes too
	lm = findObj('mblock');
	if (lm) {
		var allLinks = lm.getElementsByTagName('a');
		if (allLinks && allLinks.length > 0) {
			for(var i=0; i < allLinks.length; i++)
				addEvent(allLinks[i], 'focus', gotFocus, false);
		}
	}
	// set up home page image mouse events
	var homeimg = findObj('imgmessage');
	if (homeimg) {	// this is the home page
		var imgarea = findObj('imgarea');
		addEvent(imgarea, 'mouseover', homeImgMouseOver, false);
		addEvent(imgarea, 'mouseout',  homeImgMouseOut, false);
		homeimg.jmostate = 'none';
		homeimg.jmovis = -20;
	}
}

var homeImgInt = null;

function homeImgMouseOver(e)
{	// mouse-over starts or continues fadein
	var homeimg = findObj('imgmessage');
	if (homeimg.jmostate != 'full') {
		homeimg.jmostate = 'fadein';
		if (homeImgInt == null) 
			homeImgInt = setInterval(homeMsgFader, 50);
	}
	knackerEvent(e);
}

function homeImgMouseOut(e)
{	// mouse-out starts or continues fadeout
	var homeimg = findObj('imgmessage');
	if (homeimg.jmostate != 'none') {
		homeimg.jmostate = 'fadeout';
		if (homeImgInt == null) 
			homeImgInt = setInterval(homeMsgFader, 50);
	}
	knackerEvent(e);
}

function homeMsgFader()
{
	var homeimg = findObj('imgmessage');
	if (homeimg.jmostate == 'fadein') {
		homeimg.jmovis += 2;
		if (homeimg.jmovis >= 0 && homeimg.jmovis <= 90)
			setJMOpacity(homeimg, homeimg.jmovis, homeimg.jmostate);
		if (homeimg.jmovis >= 110) {
			homeimg.jmostate = 'full';
			var intvl = homeImgInt;
			homeImgInt = null;
			if (intvl != null) clearInterval(intvl);
		}
	} else if (homeimg.jmostate == 'fadeout') {
		homeimg.jmovis -= 2;
		if (homeimg.jmovis <  90)
			setJMOpacity(homeimg, homeimg.jmovis, homeimg.jmostate);
		if (homeimg.jmovis <= -20) {
			homeimg.jmostate = 'none';
			var intvl = homeImgInt;
			homeImgInt = null;
			if (intvl != null) clearInterval(intvl);
		}
	}
}

function setJMOpacity(div, op, jmostate)
{
	var disp = '';
	if (op == 0) {
		if (jmostate == 'fadein') {
			disp = ', block';
			div.style.display = 'block';
		} else {
			div.style.display = '';
			disp = ', none';
		}
	}
	if (op < 0) op = 0;
	if (op > 90) op = 90;
	var opFrac = op / 100;
	if (typeof div.filters == "object") {
		if (navigator.platform == 'Win32') {
			div.filters.alpha.opacity = op;
		}
	} else {
		if (typeof div.style.opacity != "undefined") {
			div.style.opacity = opFrac;
		} else if (typeof div.style.MozOpacity != "undefined") {
			div.style.MozOpacity = opFrac;
		}
	}
	//div.innerHTML = 'Click on photo for project information: ' + op + ', ' + opFrac + disp;
}

function lmMouseOver(e)
{	// leftmenu mouse-over. Take the id of the target, extract the id of the corresponding
	// line image, and change its width.
	var target = getTarget(e, 'a');
	if (target == null) return;
	var id = target.id;
	id = id.replace(/ml(\d+)/, 's$1');
	var ob = findObj(id);
	if (ob && ob.style) ob.style.width = '167px';
	knackerEvent(e);
}

function lmMouseOut(e)
{
	var target = getTarget(e, 'a');
	if (target == null) return;
	var id = target.id;
	id = id.replace(/ml(\d+)/, 's$1');
	var ob = findObj(id);
	if (ob && ob.style) ob.style.width = '';
	knackerEvent(e);
}

function gotFocus(e)
{	// kill focus box
	var target = getTarget(e, 'a');
	if (target == null) return;
	target.blur();	
}

function fixBrowserInconsistencies()
{	// this is called as part of the HTML header AFTER the CSS file.
	// Fix up font size for Mac platform.
	// We use "Arial, Helvetica, Sans-Serif" as the font for the left and submenus. Windows browser pick
	// Arial, Mac browsers pick Helvetica. The Helvetica font seems to be a bit bigger. The corrections below
	// reduce the font size to 10px for Macs.
	if (navigator.platform.toLowerCase().indexOf('mac') != -1) {
		//alert('This is a mac');
		document.writeln('<style type="text/css">');
		document.writeln(' div#leftmenu a, div#leftmenu a:link, div#leftmenu a:active, div#leftmenu a:visited,');
		document.writeln(' div#submenu a, div#submenu a:link, div#submenu a:active, div#submenu a:visited {');
		document.writeln('  font-size: 10px;');
		document.writeln(' }');
		document.writeln('</style>');
	}
}

function homeImg()
{	// do the home page image. Select the next image to show and set up the popup.
	var cook = null;
	cook = getCookie('homeImage');
	var imCnt = 0;
	
	var homeImagesArray = new Array('home1', 'world-savings', 'sunset', 'stacks', 'menlo-oaks-night', 'bain-lobby', 'livermore-gateway', 'bain-hallway', 'bron-lobby', 'peets-coffee464', 'peets-coffee467', 'nlooprd', 'GrantLine-1', 'GrantLine-2');
	
	imCnt = homeImagesArray.length;
	
	if (cook == null) {	// no cookie, select a random image
		cook = Math.random() * imCnt;
		cook = Math.round(cook);
	} else
		cook = parseInt(cook);
	cook += 1;
	if (cook >= imCnt)
		cook = 0;
	var now = new Date();
	fixDate(now);
	now.setTime(now.getTime() + 90 * 24 * 60 * 60 * 1000); // expire in 90 days
	setCookie('homeImage', cook, now);
	//alert(String(cook));

	var str = '<a href="homepopups/' + homeImagesArray[cook] + '.html" target="_blank" onclick="return popHomeWin(' + "'" + 'homepopups/' + homeImagesArray[cook] + ".html'" + ');" onfocus="this.blur();">' + '<img src="images/homeimages/' + homeImagesArray[cook] + '.jpg" alt="" /></a>';
	//alert(str);
	document.write(str);
}

// utilities

function findObj(theObj, theDoc)
{ // given a name or id, findObj returns an object reference
  var p, i, foundObj;
  
  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
  {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }
  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++) 
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
    foundObj = findObj(theObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
  
  return foundObj;
}

/*
 * Add an event handler using the W3C, MSIE, or HTML 'on' + eventType
 */
function addEvent(element, eventType, lamdaFunction, useCapture) {
    if (element.addEventListener) {
        element.addEventListener(eventType, lamdaFunction, useCapture);
        return true;
    } else if (element.attachEvent) {
        var r = element.attachEvent('on' + eventType, lamdaFunction);
        return r;
    } else {
        element['on' + eventType] = lamdaFunction;
		return true;
    }
}

function getTarget(e, tname)
{	// follow the DOM tree up until we have a node of type tname
	var ltname = tname.toLowerCase();
	var target = window.event ? window.event.srcElement : e ? e.target : null;
	while (target != document.body && target.nodeName.toLowerCase() != ltname) {
		target = target.parentNode;
	}
	if (target.nodeName.toLowerCase() == ltname)
		return target;
	else
		return null;
}

/* 
 * Kills an event's propagation and default action
 */
function knackerEvent(eventObject) {
    if (eventObject && eventObject.stopPropagation) {
        eventObject.stopPropagation();
    }
    if (window.event) {
        window.event.cancelBubble = true;
    }
    
    if (eventObject && eventObject.preventDefault) {
        eventObject.preventDefault();
    }
    if (window.event) {
        window.event.returnValue = false;
    }
}

/* 
 * Safari doesn't support canceling events in the standard way, so we must
 * hard-code a return of false for it to work.
 */
function cancelEventSafari() {
    return false;        
}

function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

function popUpWindow(URLStr, height, left, top, width)
{
	if (left == null) left = '20';
	if (top == null) top = '80';
	if (width == null) width = '465';
	if (height == null) height = '500';

	if ( window.open(URLStr, 'JMONeillPopup', 'location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width='+width+',height='+height+',left='+left+',top='+top+',screenX='+left+',screenY='+top) )
		return false; 	// suppress href
	else
		return true;
}

function popHomeWin(URLStr, height, left, top, width)
{
	if (left == null) left = '50';
	if (top == null) top = '120';
	if (width == null) width = '650';
	if (height == null) height = '600';

	if ( window.open(URLStr, 'JMONeillHomeWin', 'location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width='+width+',height='+height+',left='+left+',top='+top+',screenX='+left+',screenY='+top) )
		return false; 	// suppress href
	else
		return true;
}

addEvent(window, 'load', initEvents, false);
fixBrowserInconsistencies();

// Some of the functions in this file are adopted from various online sources, including
// Cross-browser event handling, by Scott Andrew.