// global flag
var isIE = false;

// global request and XML document objects
var req;

// retrieve XML document (reusable generic function);
// parameter is URL string (relative or complete) to
// an .xml file whose Content-Type is a valid XML
// type, such as text/xml; XML source must be from
// same domain as HTML file
function loadXMLDoc(url) {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        isIE = true;
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
    }
}

// handle onreadystatechange event of req object
function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            clearTopicList();
            buildTopicList();
         } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
         }
    }
}

// invoked by "Category" select element change;
// loads chosen XML document, clears Topics select
// element, loads new items into Topics select element
function loadDoc(evt) {
    // equalize W3C/IE event models to get event object
    evt = (evt) ? evt : ((window.event) ? window.event : null);
    if (evt) {
        // equalize W3C/IE models to get event target reference
        var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        if (elem) {
            try {
                if (elem.selectedIndex > 0) {
                    loadXMLDoc(elem.options[elem.selectedIndex].value);
                }	
            }
            catch(e) {
                var msg = (typeof e == "string") ? e : ((e.message) ? e.message : "Unknown Error");
                alert("Unable to get XML data:\n" + msg);
                return;
            }
        }
    }
}

// retrieve text of an XML document element, including
// elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    if (prefix && isIE) {
        // IE/Windows way of handling namespaces
        result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
    } else {
        // the namespace versions of this method 
        // (getElementsByTagNameNS()) operate
        // differently in Safari and Mozilla, but both
        // return value with just local name, provided 
        // there aren't conflicts with non-namespace element
        // names
        result = parentElem.getElementsByTagName(local)[index];
    }
    if (result) {
        // get text, accounting for possible
        // whitespace (carriage return) text nodes 
        if (result.childNodes.length > 1) {
            return result.childNodes[1].nodeValue;
        } else {
            return result.firstChild.nodeValue;    		
        }
    } else {
        return "n/a";
    }
}

// empty Topics select list content
function clearTopicList() {
    var ul = document.getElementById("chapters");
    while (ul.childNodes[0]) {
        ul.removeChild(ul.childNodes[0]);
    }
}

// add item to select element the less
// elegant, but compatible way.
function appendToList(ul, content) {
    var itm;
    itm = document.createElement("li");
    itm.appendChild(content);
    ul.appendChild(itm);
}

// fill Topics select list with items from
// the current XML document
function buildTopicList() {
	var datum;
    var ul = document.getElementById("chapters");
    var cols = req.responseXML.getElementsByTagName("col");
    // loop through <col> elements, and add each nested
    // <col> element to Topics select element
    for (var i = 0; i < cols.length; i++) {
		var nameflag = 0;
		datum = document.createElement("li");
		var name = document.createElement("span");
		name.setAttribute("class", "instname");
		name.appendChild(document.createTextNode(getElementTextNS("", "nom", cols[i], 0)));
		
		var instname = cols[i].getElementsByTagName("nom")[0];
		
		for (var j=0; j < instname.attributes.length; j++)
		{
			
			if (instname.attributes[j].nodeName.toLowerCase() == "website")
			{
				//debugger;
				var instlink = document.createElement("a");
				instlink.setAttribute('href', instname.attributes[j].nodeValue);
				instlink.appendChild(name);
				datum.appendChild(instlink);
				nameflag=1;
			}
		
		}
		if (nameflag == 0)
		{datum.appendChild(name); }
		
//		datum.appendChild(name);
		
		datum.appendChild(document.createElement("br"));
		
		var place = document.createElement("span");
		place.setAttribute('class', 'placename');
		place.appendChild(document.createTextNode(getElementTextNS("", "loc", cols[i], 0)));		
		datum.appendChild(place);
//		datum.appendChild(document.createTextNode(getElementTextNS("", "advis", cols[i], 0))); 

		var advisors = cols[i].getElementsByTagName("advis");
		for (var x=0; x < advisors.length; x++)
		{
			datum.appendChild(document.createElement("br"));
			datum.appendChild(document.createTextNode("Advisor: "));
			var emailflag=0;
			for (var y=0; y < advisors[x].attributes.length; y++)
			{
				
				if (advisors[x].attributes[y].nodeName.toLowerCase() == 'email')
				{
					var adv = document.createElement("a");
					var addy = "mailto:" + advisors[x].attributes[y].nodeValue;
					adv.setAttribute('href',addy);
					/*
					/* This method makes the name a hyperlink
					adv.appendChild(document.createTextNode(getElementTextNS("", "advis", cols[i], x)));
					datum.appendChild(adv);
					datum.appendChild(document.createTextNode(" (" + advisors[x].attributes[y].nodeValue + ")"));
					*/
					/* This method makes the email addy a hyperlink */
					adv.appendChild(document.createTextNode(advisors[x].attributes[y].nodeValue));
					datum.appendChild(document.createTextNode(getElementTextNS("", "advis", cols[i], x) + " ("));
					datum.appendChild(adv);
					datum.appendChild(document.createTextNode(")"));
					emailflag=1;
				}
			}
			//-----THIS WORKS-----//
			//datum.appendChild(document.createTextNode("Advisor: "));
			if (emailflag==0) {
				datum.appendChild(document.createTextNode(getElementTextNS("", "advis", cols[i], x)));
			}
		}
		ul.appendChild(datum);
    }
    // clear detail display
    // document.getElementById("details").innerHTML = "";
}


// display details retrieved from XML document
function showDetail(evt) {
    evt = (evt) ? evt : ((window.event) ? window.event : null);
    var item, content, div;
    if (evt) {
        var select = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        if (select && select.options.length > 1) {
            // copy <content:encoded> element text for
            // the selected item
            item = req.responseXML.getElementsByTagName("item")[select.value];
             
            div = document.getElementById("details");
            div.innerHTML = "";
            // blast new HTML content into "details" <div>
            div.innerHTML = content;
        }
    }
}
