var rowid;
var isLoading = false;
var nCols = 7;

var originals = {};
var cached = {};
var entTable = [];
var idsPending = [];
var fields = ['n','p','a','l','ph','e','x'];
var isSecondary = location.href.indexOf('secondary') > 0;

var bufimgs = {}; // for MacIE
var entNames = ['b','w'];
var sortState = {field:'n', order:1}; // 1 == ascending, -1 = descending
var scope = 0; // show all initially
var searchTimerId = -1;
var MacIE = ( navigator.userAgent.indexOf('MSIE') >= 0 && navigator.userAgent.indexOf('Mac') >= 0 );

var imgpath = "/images/stock/directory/";
// preload sort bar images -------------------
var nImgAct = new Image();
nImgAct.src = imgpath+"Name_s.gif";
var nImgInact = new Image();
nImgInact.src = imgpath+"Name_ns.gif";
var phImgAct = new Image();
phImgAct.src = imgpath+"Phone_s.gif";
var phImgInact = new Image();
phImgInact.src = imgpath+"Phone_ns.gif";
var lImgAct = new Image();
lImgAct.src = imgpath+"Location_s.gif";
var lImgInact = new Image();
lImgInact.src = imgpath+"Location_ns.gif";
var eImgAct = new Image();
eImgAct.src = imgpath+"Email_s.gif";
var eImgInact = new Image();
eImgInact.src = imgpath+"Email_ns.gif";

var dImgAct, dImgInact, pImgAct, pImgInact, aImgAct, aImgInact, phImgAct, phImgInact, xImgAct, xImgInact;
if (isSecondary) {
	dImgAct = new Image();
	dImgAct.src = imgpath+"Department_s.gif";
	dImgInact = new Image();
	dImgInact.src = imgpath+"Department_ns.gif";
} else {
	pImgAct = new Image();
	pImgAct.src = imgpath+"Position_s.gif";
	pImgInact = new Image();
	pImgInact.src = imgpath+"Position_ns.gif";
	aImgAct = new Image();
	aImgAct.src = imgpath+"Affiliation_s.gif";
	aImgInact = new Image();
	aImgInact.src = imgpath+"Affiliation_ns.gif";
	xImgAct = new Image();
	xImgAct.src = imgpath+"Ext_s.gif";
	xImgInact = new Image();
	xImgInact.src = imgpath+"Ext_ns.gif";
}

shimImg = new Image();
shimImg.src = "/images/stock/shim.gif";
upArrowImg = new Image();
upArrowImg.src = imgpath+"Arrow_up.gif";
downArrowImg = new Image();
downArrowImg.src = imgpath+"Arrow_down.gif";
wArrowImg = new Image();
wArrowImg.src = imgpath+"d_arrow.gif";
arrowImg = new Image();
arrowImg.src = imgpath+"arrow.gif";

var radAct = new Image();
radAct.src = '/images/stock/Radio_s.gif';
var radInact = new Image();
radInact.src = '/images/stock/Radio_ns.gif';

// 3 status messages
var statusload = new Image();
statusload.src = imgpath+"Status_load.gif";
var statusfind = new Image();
statusfind.src = imgpath+"Status_find.gif";
var statussort = new Image();
statussort.src = imgpath+"Status_sort.gif";

// -------------------------------------------

function notify(result)
{ // result is an array of nodes
	for (var i = 0; i < result.length; i++) update(result[i]);
	isLoading = false;
	idsPending.length = 0; // truncate
	setStatusMessage("");
}

function update(result)
{
	var doc = window.document;
	var id = result.firstChild.firstChild.nodeValue;
	var imgsrc = result.childNodes[1].firstChild.nodeValue;
	
	var tr = doc.getElementById('i'+id);
	var td = tr.childNodes[1];
	td.removeChild(td.firstChild); // remove the loading message
	
	var ntbl = doc.createElement('table');
	ntbl.style.margin = ntbl.style.padding = "0px";
	ntbl.setAttribute("cellPadding",0);
	ntbl.setAttribute("cellSpacing",0);	
	ntbl.style.width = "100%";
	
	var ntbody = doc.createElement('tbody');
	var ntr = doc.createElement('tr');
	var ntd1 = doc.createElement('td');
	ntd1.style.verticalAlign = "top";
	ntd1.style.width = "112px";
	ntd1.style.paddingTop = "3px";
	ntr.appendChild(ntd1);
		
	var ntd2 = doc.createElement('td');
	ntd2.style.verticalAlign = "top";
	ntd2.style.width = "210px";
	ntd2.style.paddingTop = "3px";
	ntd2.innerHTML = result.childNodes[2].innerHTML + "\n";
	ntr.appendChild(ntd2);
		
	var ntd3 = doc.createElement('td');		
	ntd3.style.verticalAlign = "top";
	ntd3.style.borderLeft = "1px solid #CCCCCC";
	ntd3.style.width = "385px";
	ntd3.style.height = "112px";
	ntd3.style.paddingTop = ntd3.style.paddingRight = "3px";
	ntd3.style.paddingLeft = "6px";
	ntd3.innerHTML = result.childNodes[3].innerHTML + "\n";
	ntr.appendChild(ntd3);
	
	ntbody.appendChild(ntr);
	ntbl.appendChild(ntbody);
	td.appendChild(ntbl);
	
	if ( imgsrc != "" ) {	
		if ( MacIE ) {
			var bufimg = new Image();
			bufimgs[imgsrc] = ntd1; // map an id to the src	-- this means each image must be unique -- at least for each request
			bufimg.onload = function()
			{
				var img = this.src.substr(this.src.lastIndexOf('/')+1,this.src.length);
				var td = bufimgs[img];
				var doc = window.document;
				var img = doc.createElement("img");
				img.style.width = "100px";
				img.setAttribute('src',this.src);
				td.appendChild(img);
				img.style.marginLeft = "5px";
				img.style.marginTop = "5px";			
				img.style.border = "1px solid #666666";				
				delete(bufimgs[img]);
			}
			bufimg.src = "/images/personnel/"+imgsrc;
		} else {
			var img = doc.createElement('img');
			img.style.width = "100px";
			//img.style.paddingLeft = "5px";
			//img.style.paddingTop = "5px";
			img.style.marginLeft = "5px";
			img.style.marginTop = "5px";			
			img.style.border = "1px solid #666666";		
			img.src = "/images/personnel/"+imgsrc;
			ntd1.appendChild(img);
		}
	}
}

function expand(prev)
{// prev is the table row that comes before where the new tr should be added
	prev = prev.parentNode;
	var rowid = prev.id;
	var parent = prev.parentNode;
	var next = prev.nextSibling;
	
	// update entTable with new state
	for ( var i = 0; i < entTable.length; i++ ) {
		if ( entTable[i].id == rowid ) {
			entTable[i].state = 1;
			break;
		}
	}
	if ( cached[rowid] ) { // already cached
		cached[rowid].className = prev.className;
//		cached[rowid].firstChild.className = prev.firstChild.className;
//		cached[rowid].lastChild.className = prev.lastChild.className;
		originals[rowid] = parent.removeChild(prev);
		if ( next == null ) parent.appendChild(cached[rowid]);
		else parent.insertBefore(cached[rowid],next);
		delete(cached[rowid]);
		return;
	}
	var doc = window.document;	
	var tr = doc.createElement("tr");
	tr.setAttribute("id",rowid);
	tr.className = prev.className;
			
	var tdshim = doc.createElement("td");
	
	tdshim.className = prev.firstChild.className;
	tr.appendChild(tdshim);
	
	var td = doc.createElement("td");
	td.setAttribute("colSpan",nCols);
	td.style.height = "125px";
	td.style.width = "737px";
	var style = prev.lastChild.className;
	if (style.length > 3) style = style.substr(0,3);
	td.className = style;
	td.style.padding = "5px";
	td.style.paddingTop = "2px";

	setStatusMessage("");
	setStatusMessage("load");

	var name = doc.getElementById(rowid+'n').firstChild.nodeValue;
	var first = name.substr(name.lastIndexOf(' '),name.length);
	var last = name.substr(0,name.lastIndexOf(','));
	td.appendChild(doc.createTextNode("Loading " + first + " " + last ));
	tr.appendChild(td);	
	
	originals[rowid] = parent.removeChild(prev);
	parent.insertBefore(tr,next);
	
	// add this after adding tr to document -- will fail on Mac IE otherwise
	var img = doc.createElement('img');
	tdshim.appendChild(img);	
	img.setAttribute('src',wArrowImg.src);
	img.className = 'arw';
	tdshim.onclick = function(){ contract(this.parentNode); }
	td.setAttribute("colSpan",nCols);	
	var id = rowid.substr(1,rowid.length);
	isLoading = true;
	idsPending[idsPending.length] = id;
	window.frames.lookup.location.replace("/modperl/person.pl?id="+idsPending.join('-'));
}

function contract(prev)
{	// should only be called if the rowid has been copied into originals object
	// get the id
	if (isLoading) return;
	rowid = prev.id;	
	if ( originals[rowid] == null ) return;
	var parent = prev.parentNode;

	// update entTable with new state
	for ( var i = 0; i < entTable.length; i++ ) {
		if ( entTable[i].id == rowid ) {
			entTable[i].state = 0;
			break;
		}
	}
	var next = prev.nextSibling;
	originals[rowid].className = prev.className;
//	originals[rowid].firstChild.className = prev.firstChild.className;
//	originals[rowid].lastChild.className = prev.lastChild.className;
	cached[rowid] = parent.removeChild(prev);
	if ( next == null ) parent.appendChild(originals[rowid]); // this should never happen anymore
	else parent.insertBefore(originals[rowid],next);
	delete(originals[rowid]);
}

function _expand() { expand(this); }

function init(ver)
{
	document.getElementById('nArrow').setAttribute('src',upArrowImg.src);
	document.getElementById('nImg').setAttribute('src',nImgAct.src);
	if (ver == 2) {
		fields = ['n','d','l','ph','e'];
		nCols = 5;
		document.getElementById('dImg').setAttribute('src',dImgInact.src);
	} else {
		document.getElementById('pImg').setAttribute('src',pImgInact.src);
		document.getElementById('aImg').setAttribute('src',aImgInact.src);
		document.getElementById('xImg').setAttribute('src',xImgInact.src);		
	}
	document.getElementById('lImg').setAttribute('src',lImgInact.src);
	document.getElementById('phImg').setAttribute('src',phImgInact.src);
	document.getElementById('eImg').setAttribute('src',eImgInact.src);

	window.frames.lookup.location.replace("/modperl/person.pl");
	if (!MacIE) {
		document.getElementById('filter').style.visibility = 'visible';
		document.forms[0].query.onkeyup = function()
		{
			if ( searchTimerId != -1 ) window.clearTimeout(searchTimerId);
			if (document.forms[0].query.value.length >= 2 || document.forms[0].query.value.length == 0) searchTimerId = 	window.setTimeout("doSearch()",1500);		
		}
	}
	buildTable();
}

function findTag(id,tags,result)
{
	var n;
	for (n = -1; ++n < tags.length && !result[0];) {
		if (tags[n].hasChildNodes() && tags[n].firstChild.hasChildNodes()) findTag(id,tags[n].childNodes,result);
		else if (tags[n].id && tags[n].id.indexOf(id)==0) {
			result[0] = tags[n].id.substr(id.length,tags[n].id.length);
			result[1] = tags[n];
		}
	}
}
function buildTable()
{
	var entries = document.getElementById("entries").firstChild.childNodes; // get tbody, not table
	var i, j=0, k, n;
	var result = [0,0];
	for (i = 0; i < entries.length; i++) {
		if ( entries[i].id.indexOf('i') == 0 ) {
			var id = entries[i].id;
			var entry = entTable[j] = {active: true, state: 0, id: id}; // whether or not the entry is being shown; minimized, maximized		
			if (!entries[i].hasChildNodes()) continue;	
			var props = entries[i].childNodes; // props are td elements
			props[0].onclick = _expand; // function() { x(this); }
//			props[0].firstChild.setAttribute('src',arrowImg.src);	
			for (k = 0; k < props.length; k++) {
				result[0] = 0;
				if (props[k].id.indexOf(id)==0) {
					result[0] = props[k].id.substr(id.length,props[k].id.length);
					result[1] = props[k];
					if (result[0] == 'n') props[k].onclick = _expand; // function() { x(this); }	
				} else {
					if (!props[k].hasChildNodes()) continue;
					findTag(id,props[k].childNodes,result);
				}	
				if (!result[0]) continue; // id not found
				var tag = result[1];
				if (result[0] == 'l' && tag != null) {
					entry[result[0]] = "";
					for (var m = 0; m < tag.childNodes.length; m++)
						entry[result[0]] += tag.childNodes[m].firstChild.nodeValue;
				} else {
					entry[result[0]] = (tag != null && tag.hasChildNodes()) ? tag.firstChild.nodeValue : "";
				}	
			}
			j++;
		}
	}
}

function setStatusMessage(s)
{
	var msg = document.getElementById("statusmsg");
	if (s.length > 0)
		msg.setAttribute('src',eval("status"+s).src);
	else
		msg.setAttribute('src',shimImg.src);
}

function blurSearch(obj)
{
//	if (obj.value != "") return;
//	obj.value = "Search directory";
//	obj.style.color = "#000000";	
}
function prepSearch(obj)
{
	if (obj.value == "Search directory") obj.value = "";
	obj.style.color = "#000000";
}
function setScope(val)
{
	var id = parseInt(val);
	var act = document.getElementById("rad"+val);
	var inact = document.getElementById("rad"+parseInt(1-id));
	act.setAttribute('src',radAct.src);
	inact.setAttribute('src',radInact.src);
	scope = val;
}
function doSearch()
{
// even though we may only be showing a fraction of entries in entTable, they're all correctly sorted.
	window.clearTimeout(searchTimerId);
	if (MacIE) return;	
	setStatusMessage("find");
	window.setTimeout("_doSearch()",100);
}
function _doSearch()
{
	var q = document.forms[0].query.value.toLowerCase().split(' ');
	var found, i, j, k, m, nactive = 0, nmatches = 0;
	var nomatchmsg = document.getElementById('nomatch');
	if ( nomatchmsg != null ) nomatchmsg.parentNode.removeChild(nomatchmsg);
	for ( i = 0; i < entTable.length; i++ ) {
		found = 0;
		for ( m = 0; m < q.length; m++ ) {
			for ( j = 0; j < fields.length; j++ ) {
				if ( entTable[i][fields[j]].toLowerCase().indexOf(q[m]) >= 0 ) {
					found++;
					break;
				}
			}
		}
		if (found < q.length && entTable[i].active) {
			entTable[i].active = false;
			var ent = document.getElementById(entTable[i].id);
			ent = ent.parentNode.removeChild(ent); // save the node for use later
			(entTable[i].state) ? cached[ent.id] = ent : originals[ent.id] = ent;					
		} else if ( found == q.length ) {
			nmatches++;
			var ent = null;
			if (!entTable[i].active) {
				if (scope) continue;
				entTable[i].active = true;
				var id = entTable[i].id; // get the entry from originals or cached	
				if (entTable[i].state==0) ent = originals[id];
				if (ent == null) ent = cached[id];
				if (ent == null) continue;
				// insert it into the document; get the id of nextSibling
				k = i;
				while (++k < entTable.length && !entTable[k].active);
				var next = document.getElementById( (k >= entTable.length) ? 'footer' : entTable[k].id);
				if (ent.className != 'r'+entNames[nactive%2]) {
					ent.className = 'r'+entNames[nactive%2];
					ent.firstChild.className = 'el'+entNames[nactive%2];
					if (isSecondary) ent.lastChild.className = 'er'+entNames[nactive%2]+'lk';
					else ent.lastChild.className = 'er'+entNames[nactive%2];
				}	
				next.parentNode.insertBefore(ent,next);
			} else { // already active, just get node to update styling
				ent = document.getElementById(entTable[i].id);
				if (ent.className != 'r'+entNames[nactive%2]) {
					ent.className = 'r'+entNames[nactive%2];
					ent.firstChild.className = 'el'+entNames[nactive%2];
					if (isSecondary) ent.lastChild.className = 'er'+entNames[nactive%2]+'lk';
					else ent.lastChild.className = 'er'+entNames[nactive%2];					
				}	
			}
			nactive++;
		}
	}
	if ( nmatches == 0 ) {
		var footer = document.getElementById('footer');
		var tr = document.createElement('tr');
		tr.setAttribute('id',"nomatch");
		tr.className = "rw";
		var tdl = document.createElement('td');
		tdl.className = 'elw';
		tdl.style.borderWidth = "0px";
		tr.appendChild(tdl);
		var td = document.createElement('td');
		tr.appendChild(td);
		td.style.color = "#999999";
		td.setAttribute('colSpan',nCols-1);
		td.setAttribute('width','100%');
		td.style.textAlign = "center";
		td.appendChild(document.createTextNode('No matches'));
		var tdr = document.createElement('td');
		tdr.className = 'erw';
		tr.appendChild(tdr);		
		footer.parentNode.insertBefore(tr,footer);
		td.setAttribute('colSpan',nCols-1);
	}
	setStatusMessage("");
}
// -- MAIN SORTING HANDLERS -----------------------------------------
function sortOn(field)
{
	if (MacIE) return;	
	if (sortState.field == field) {
		sortState.order = -1*sortState.order;
		document.getElementById(field+'Arrow').setAttribute('src',(sortState.order==1) ? upArrowImg.src : downArrowImg.src);
	} else {
		document.getElementById(sortState.field+'Img').setAttribute('src',eval(sortState.field+"ImgInact").src);
		document.getElementById(sortState.field+'Arrow').setAttribute('src',shimImg.src);	
		var col = document.getElementById(sortState.field+"col");
		col.className = 'ch';
		col = document.getElementById(field+"col");
		col.className = 'cha';
		document.getElementById(field+'Img').setAttribute('src',eval(field+"ImgAct").src);
		document.getElementById(field+'Arrow').setAttribute('src',(sortState.order==1) ? upArrowImg.src : downArrowImg.src);		
		sortState.field = field;
	}
	setStatusMessage("sort");
	window.setTimeout("_sortOn()",100);
}
function _sortOn()
{
	entTable.sort(sort);
	var entries = document.getElementById("entries").firstChild.childNodes;
	var i = 1, j = 0;
	while (++i < entries.length && entries[i].id.indexOf('i') != 0);
	if (i < entries.length) {
		var first = entries[i];
		if (MacIE) {
			macSortParams = [entries,0,first];
			_macSortOn();
			return;
		}		
		var parent = first.parentNode;
		for (i = 0; i < entTable.length; i++) {
			if ( !entTable[i].active ) continue; // the entry is hidden; keep it that way
			var el = document.getElementById(entTable[i].id);
			if (el.className != 'r'+entNames[j]) {
				el.className = 'r'+entNames[j];
				el.firstChild.className = 'el'+entNames[j];
				if (isSecondary) el.lastChild.className = 'er'+entNames[j]+'lk';
				else el.lastChild.className = 'er'+entNames[j];
			}
			if (el == first) first = el.nextSibling;
			else parent.insertBefore(parent.removeChild(el),first);
			j = 1-j;
		}
	}
	setStatusMessage("");
}
// -- SORTING FUNCTIONS ---------------------------------------------
function sort(a,b)
{
	var lhs = a[sortState.field];
	var rhs = b[sortState.field];
	
	if ( lhs < rhs ) return sortState.order*-1;
	if ( lhs == rhs )
		if (sortState.field == 'n') return 0;
		else {
			lhs = a.n;
			rhs = b.n;
			if ( lhs < rhs ) return sortState.order*-1;
			if ( lhs == rhs ) return 0;	
		}
	return sortState.order;	
}
// -- HANDLE LINKING ---------------------------------------------------
function e(id,n,d,b)
{
	if (b == null)
		document.write('<td class="elk" id="i' + id + 'e" onclick="a(this)">' + n + '@' + d + '</td>');
	else
		document.write('<td class="er' + b + 'lk" id="i' + id + 'e" onclick="a(this)">' + n + '@' + d + '</td>');
}

function a(val,targ)
{
	if (typeof(val)=='object') val = val.firstChild.nodeValue;
	var regex = /\A\d+\Z/;
	if (val.indexOf('.')<0 && (regex.test(val) || (targ && targ.indexOf('bldg') >= 0)))
		val = "/main/directions.html#" + val;
	else if (val.indexOf(' Lab') > 0)
		val = "/faculty/" + val.substr(0,val.indexOf(' Lab')).toLowerCase() + "/";
	var linker = document.getElementById('linker');
	if (val.indexOf('@') > 0 && val.indexOf('mailto:') < 0) val = 'mailto:' + val;
	if (typeof(linker.click) == 'function') {
		if (val.indexOf('@') > 0)
			linker.setAttribute('target','');
		else	
			linker.setAttribute('target',targ);
		linker.setAttribute('href',val);
		linker.click();
	} else {
		if (targ && val.indexOf('@') < 0) 
			window.open(val,targ);
		else
			window.location = val;
	}
}



/*
var macSortParams; // for MacIE
function _macSortOn()
{
	var entries = macSortParams[0];
	var from = macSortParams[1];
	var first = macSortParams[2];
	var i = 1, j = 0;
	var parent = first.parentNode;
	var to = Math.min(entTable.length,from+10);
	for (i = from; i < to; i++) {
		if ( !entTable[i].active ) continue; // the entry is hidden; keep it that way
		var el = document.getElementById(entTable[i].id);
		if (el.className != 'r'+entNames[j]) {
			el.className = 'r'+entNames[j];
			el.firstChild.className = 'entl'+entNames[j];
			el.lastChild.className = 'entr'+entNames[j];
		}
		if (el == first) first = el.nextSibling;
		else parent.insertBefore(parent.removeChild(el),first);
		j = 1-j;
	}
	if (to == entTable.length) setStatusMessage("");
	else {
		macSortParams[1] = to;
		macSortParams[2] = first; 
		window.setTimeout("_macSortOn()",100);	
	}
}
*/