var TheExhibitXML, TheTerms, ThePath, CurrentObjectKey, CurrentTermIndex, theinterval;


function gallery (seq)
{
	termclick (CurrentTermIndex + seq, 1);
}


function loadxml (url, handler, path, enterkey) 
{
	//save as global for future use -- must be set before "xmldoc.load"
	if (url.indexOf ("request=exhibit") > -1)
	{
		ThePath = path;
		document.getElementById('docspan').innerHTML = "<br>Loading exhibition ...";
	}

	// This function loads the XML document from the specified URL, and when
	// it is fully loaded, passes that document and the url to the specified
	// handler function.  This function works with any XML document

    	// Use the standard DOM Level 2 technique, if it is supported
    	if (document.implementation && document.implementation.createDocument) 
    	{
        	xmldoc = document.implementation.createDocument("", "", null);
        	xmldoc.onload = function() { handler (xmldoc, path, enterkey); };
        	xmldoc.load (url);
    	}

    	// Otherwise use Microsoft's proprietary API for Internet Explorer
   	else if (window.ActiveXObject) 
    	{ 
		try		
		{
			//version 4
			xmldoc = new ActiveXObject("Msxml2.DOMDocument.4.0");
		}
	        catch (e)
		{
			try
			{
				//version 3 (could be DOMDocument.3.0)
				xmldoc = new ActiveXObject("Msxml2.DOMDocument");
				//"javascript and dhtml cookbook, p. 424 also as this:
				//xmldoc = new ActiveXObject("Msxml.DOMDocument");
				//	-- which it refers to as "backward-compatible"
			}
			catch (e)
			{
				//any version 1 thru 3
		        	xmldoc = new ActiveXObject("Microsoft.XMLDOM");
			}
		}

		/*030930 per iva koberg -- didn't help in any combination
		xmldoc.async = false;
		xmldoc.validateOnParse = false;
		xmldoc.resolveExternals = false;
		*/

        	xmldoc.onreadystatechange = function() 
		{ 
			//alert ("ready state:" + xmldoc.readyState);
            		if (xmldoc.readyState == 4)
			{
				var err = xmldoc.parseError;
				if (err.errorCode == 0)
					handler (xmldoc, path, enterkey);
				else
					alert ("Load failed. Reason: " + err.reason);
			}
        	};
        	xmldoc.load (url);
    	}

	//save as global for future use -- assuming it has to be after load
	if (url.indexOf ("request=exhibit") > -1)
	{
		TheExhibitXML = xmldoc;
	}
}

function makepage (xmldoc, path, enterkey) 
{
	//030922 to reset when arrived from Back button
	top.document.getElementById('TBframeset').rows='0,*';
	top.document.getElementById('LCRframeset').cols='0,0,*';


	//fill the topdiv
	var buf = this.document.getElementById ("topbuffer");
	buf.src = "/mweb/" + path + "/exh_top_nav.htm";


	//menu items not part of exhibit data
	var dept, name, lcpath;
	lcpath = path.toLowerCase ();
	if (lcpath.indexOf ("aa/") == 0)
	{
		dept = "american";
		name = "American Art";
	}
	else if (lcpath.indexOf ("ct/") == 0)
	{
		dept = "cost";
		name = "Costume &amp; Textiles";
	}
	document.getElementById('menuspan').innerHTML = "<a class=menu href='http://www.lacma.org'>LACMA Home</a>" +
			"<br><a class=menu href='/mwebcgi/mweb.exe?request=browsetop'>Featured Collections Home</a>" +
			"<br><a class=menu href='/mwebcgi/mweb.exe?request=browpage&dept=" + dept + "'>" + name + " Home</a><br>";


    	// Now find all <term> elements in our xml document
    	TheTerms = xmldoc.getElementsByTagName ("term");

    	// Loop through the terms
    	for (var i = 0; i < TheTerms.length; i++) 
    	{
	        var trmnode = TheTerms [i];
        	var trmlevel = parseInt (trmnode.getAttribute ("level"));
        	var trmgallery = parseInt (trmnode.getAttribute ("gallery"));
        	var trmpopup = parseInt (trmnode.getAttribute ("popup"));
		if ((trmlevel > 0) && (trmgallery == 0)) //skip top level & galleries
		{
	        	var trmname = trmnode.getElementsByTagName ("name") [0].firstChild.data;

			var br = document.createElement ("br");
        		document.getElementById('menuspan').appendChild (br);
			var menuitem = document.createElement ("a");
			menuitem.className = "menu";

			//this is the sequence in the menu, not the same as the term number,
			//	as galleries are not in the menu
			menuitem.setAttribute ("id", "item" + i);

			//prevent status line
			menuitem.onmouseover = function () {window.status=''; return true;};

			if (trmpopup == 1)
				menuitem.setAttribute ("href", "javascript:termpopup (" + i + ")");
			else
				menuitem.setAttribute ("href", "javascript:termclick (" + i + ")");

			if (trmlevel == 1) 
				menuitem.className = "emenu";
			else 
				menuitem.className = "emenusub";

			var theterm = document.createElement ("span");
			if (trmlevel == 1)
				theterm.innerHTML = trmname;
			else if (trmlevel == 2)
				theterm.innerHTML = "<font color='#ffcc66'>&#8226;</font>&nbsp;&nbsp;" + trmname;
			else if (trmlevel == 3)
				theterm.innerHTML = "&nbsp;&nbsp;&nbsp;<font color='#ffcc66'>&#8226;</font>&nbsp;&nbsp;" + trmname;
			menuitem.appendChild (theterm);
	        	document.getElementById('menuspan').appendChild (menuitem);
		}
    	}

	if (enterkey > 1)
	{
		for (var y = 1; y < TheTerms.length; y++)
		{
			if (TheTerms [y].getAttribute ("key") == enterkey)
			{
				termclick (y);
				break;
			}
		}
		
	}
	else
		termclick (1);
}


function makerecord (xmldoc, path) //path not needed
{
	dataspan.innerHTML = "";
	var btn = document.createElement ("button");
	btn.onclick = function () {javascript:termclick (CurrentTermIndex)};
	btn.appendChild (document.createTextNode ("Back"));
	dataspan.appendChild (btn);

    	var maintable = document.createElement ("table");
    	//maintable.setAttribute ("border", "1");
    	dataspan.appendChild (maintable);

	//var caption = "Here is your record";
    	//maintable.createCaption().appendChild(document.createTextNode(caption));
    	//duplicate of above?//dataspan.appendChild (maintable);
    

	//image table
	var imagetable = document.createElement ("table");
    	//imagetable.setAttribute ("border", "1");

	//find image info in TheExhibitXML (the Full Record does not have the path)
	var objnodes = TheExhibitXML.getElementsByTagName ("object");
        for (var i = 0; i < objnodes.length; i++) 
	{
		if (objnodes [i].getAttribute ("key") == CurrentObjectKey)
			break;
	}
	//we're assuming all objects have images -- mandatory for OEs
       	var imgnodes = objnodes [i].getElementsByTagName ("image");
        for (var j = 0; j < imgnodes.length; j++) 
	{
	       	var imgnode = imgnodes [j];
	       	var ikey = imgnode.getAttribute ("key");
       		var imgfilename = imgnode.getElementsByTagName ("filename") [0].firstChild.data;
	       	var imgfolder = imgnode.getElementsByTagName ("folder") [0].firstChild.data;

		var theimg = document.createElement ("img");

		if (j == 0)
			theimg.setAttribute ("src", "/mwebimages/" + imgfolder + "/full/" + imgfilename + ".jpg");
		else
			theimg.setAttribute ("src", "/mwebimages/" + imgfolder + "/thumb/" + imgfilename + ".jpg");

		theimg.setAttribute ("border", "0");
		theimg.setAttribute ("height", theimg.getAttribute ("height")/2);
		theimg.setAttribute ("width", theimg.getAttribute ("width")/2);

		var imgitem = document.createElement ("a");
		imgitem.onmouseover = function () {window.status=''; return true;};
		imgitem.setAttribute ("href", "/mwebcgi/mweb.exe?request=imagesave&hex=" + imgfilename + "&w=100&h=100");
		imgitem.appendChild (theimg);

		var irow = imagetable.insertRow ();
		var icell = irow.insertCell ();
		icell.appendChild (imgitem);
	}


	//data table
	var datatable = document.createElement ("table");
	datatable.cellpadding = 2;
	datatable.cellspacing = 3;
    	//datatable.setAttribute ("border", "1");
	var lastenglish = "";
	var nodes = xmldoc.documentElement.childNodes;
	var hr_done = false;
	for (var i = 0; i < nodes.length; i++)
	{
		if ((nodes.item (i).getAttribute ("visible") > 0) && !hr_done)
		{
			var hrcell = document.createElement ("td");
			hrcell.innerHTML = "<hr>";
        		var drow = datatable.insertRow ();
			drow.appendChild (hrcell);
			hr_done = true;
		}


		var english;
		if ((nodes.item (i).nodeName == lastenglish) ||
				(nodes.item (i).getAttribute ("visible") < 0))
			english = "";
		else
			english = "<b>" + nodes.item (i).nodeName.replace (/_/g, " ") + "</b><br>";

		lastenglish = nodes.item (i).nodeName;


		var fielddata = document.createElement ("td");
		fielddata.className = "results";
		//031008 make links where required
		var linkkey = nodes.item (i).getAttribute ("key");
		if (linkkey)
		{
	        	var thelink = english + 
					"<a class=resultslink href=\"javascript:document.mainform.request.value='record'; " +
					"document.mainform.key.value=" + linkkey + "; " +
					"document.mainform.submit ();\" " +
					"onmouseover=\"window.status='Record " + linkkey + "'; return true;\" " +
					"onmouseout=\"window.status=''; return true;\">" +
					nodes.item (i).firstChild.data + 
					"</a>";
			fielddata.innerHTML = thelink;
		}
		else
		{
			if (nodes.item (i).getAttribute ("visible") < 0)
				fielddata.innerHTML = "<b>" + nodes.item (i).firstChild.data + "</b>";
			else
				fielddata.innerHTML = english + nodes.item (i).firstChild.data;
		}


        	var drow = datatable.insertRow ();
		drow.appendChild (fielddata);
	}

	if (!hr_done)
	{
		var hrcell = document.createElement ("td");
		hrcell.innerHTML = "<hr>";
       		var drow = datatable.insertRow ();
		drow.appendChild (hrcell);
	}


	//add imagetable and datatable to maintable
       	var mrow = maintable.insertRow ();
	var mcell = mrow.insertCell ();
	mcell.appendChild (imagetable);
	var mcell = mrow.insertCell ();
	mcell.appendChild (datatable);

	var btn = document.createElement ("button");
	btn.onclick = function () {javascript:termclick (CurrentTermIndex)};
	btn.appendChild (document.createTextNode ("Back"));
	dataspan.appendChild (btn);
}


function termclick (trmindex, gallery)
{
	if (!gallery)
	{
		CurrentTermIndex = trmindex;

		//reset links to default color
		for (var y = 0; y < TheTerms.length; y++)
		{
			yy = this.document.getElementById ("item" + y);
			if (yy)	//galleries don't have menu items
				yy.style.cssText = "";	//so it reverts to the default in <style>
		}

		//make this one red
		this.document.getElementById ("item" + trmindex).style.cssText = "color: #ff6600";
	}

	//reset after Full Record
	document.getElementById('docspan').style.width = '35%';
	document.getElementById('dataspan').style.left = '55%'; 
	document.getElementById('dataspan').style.width = '45%'; 

	if (!gallery)
	{
		document.getElementById('docspan').innerHTML = "";
        	var docnode = TheTerms [trmindex].getElementsByTagName ("document") [0];
		if (docnode) 
		{
			var docfilename = docnode.getElementsByTagName ("filename") [0].firstChild.data;
			var buf = this.document.getElementById ("docbuffer");

		    	//have to see if folder node exists before getting firstChild -- we need to check folder
			//	for each docnode because they may not be in ThePath: for example, comments.asp 
			//	is common to all OEs, so is in /mweb/
		    	if (docnode.getElementsByTagName ("folder") [0])
	    		{
				var docfolder = docnode.getElementsByTagName ("folder") [0].firstChild.data;
				buf.src = "/mweb/" + docfolder + "/" + docfilename;
		    	}
	    		else
				buf.src = "/mweb/" + docfilename;
		}
	}


	//msg for CT only
	if (ThePath.toLowerCase ().indexOf ("ct/") == 0)
		document.getElementById('dataspan').innerHTML = "<p class=tn align=center>* Indicates object on display</p>";
	else
		document.getElementById('dataspan').innerHTML = "";

    	//when term clicked, get its objects and display the objects' images
        var objnodes = TheTerms [trmindex].getElementsByTagName ("object");
        for (var j = 0; j < objnodes.length; j++) 
	{
            	var objnode = objnodes [j];
	    	var objkey = objnode.getAttribute ("key");
	       	var objtil = objnode.getElementsByTagName ("title") [0].firstChild.data;	//will fail if no title
		var objflags = objnode.getElementsByTagName ("isinexhibit");
		if (objflags.length > 0)
			var objflag = objflags [0].firstChild.data;
     	    	var imgnodes = objnode.getElementsByTagName ("image");
	        for (var k = 0; k < imgnodes.length; k++) 
	    	{
			var imgnode = imgnodes [k];
		    	if (imgnode)
			{
				var imgitem = document.createElement ("a");
				imgitem.setAttribute ("href", "javascript:tnclick (" + objkey + ")");

		        	var imgfilename = imgnode.getElementsByTagName ("filename") [0].firstChild.data;
		        	var imgfolder = imgnode.getElementsByTagName ("folder") [0].firstChild.data;
				var theimg = document.createElement ("img");
				theimg.className = "tn";
				theimg.setAttribute ("src", "/mwebimages/" + imgfolder + "/thumb/" + imgfilename + ".jpg");
				theimg.setAttribute ("alt", objtil);
				theimg.setAttribute ("align", "top");

				//this also has the effect of not showing images that can't be found
				//	-- but any borders still show for the missing images (with h & w = 0)
				//theimg.setAttribute ("height", theimg.getAttribute ("height")/2);
				//theimg.setAttribute ("width", theimg.getAttribute ("width")/2);

				imgitem.appendChild (theimg);

				//use spans to keep * with tn (so * doesn't wrap)
				//titles are too long for size of tn, also problems putting under TNs, centering
				//imgbr causes break BEFORE each imgspan instead of inside them
				var imgspan = document.createElement ("span");
				imgspan.appendChild (imgitem);
				imgspan.className = "tn";

				imgtil = document.createElement ("p");
				imgtil.className = "tn";
				imgtil.innerHTML = objtil;	//converts entities, createTextNode doesn't
				imgspan.appendChild (imgtil);

				//030926 shows most TNs but not all (without this, shows none on first click)
				//	-- "block" does the same as "inline"
				theimg.setAttribute ("display", "inline");
				imgitem.setAttribute ("display", "inline");
				imgspan.setAttribute ("display", "inline");

				if (objflag == "Yes")
					imgspan.appendChild (document.createTextNode ("*"));
				document.getElementById('dataspan').appendChild (imgspan)
			
				/*the "halfsize" method is much faster
				//031007 moved here so image size known before trying to reduce it
				// -- delay required to wait for image to be loaded. can't use setTimeout 
				//		because execution continues and references are messed up
				var x = 0;
				while (x == 0)
				{
					x = checksize (theimg);
				}

				theimg.setAttribute ("height", theimg.getAttribute ("height")/2);
				theimg.setAttribute ("width", theimg.getAttribute ("width")/2);
				*/
		    	}
		}
	}

	//031007 tried 0, 100, 200, 1000 delays, but still got some microTNs in each
//-- clearly they are not because image not yet
//loaded, but some other reason. clicking on the menu item again does display the image correctly
	setTimeout ("halfsize ()", 0);
}


/*
function checksize (theimg)
{
	//for some reason, images cb shown about 30 high by 5 wide
	//	-- note: the IE "not-found" image is 30 high, and as wide as the title would be if not wrapped
	if (theimg.getAttribute ("width") > 50)
		return 1;
	else
		return 0;
}
*/


//031007 this works but images shown full-size momentarily
function halfsize ()
{
	var theimages = document.getElementById ('dataspan').getElementsByTagName ('img');
	for (var i = 0; i < theimages.length; i++)
	{
		theimages [i].setAttribute ("height", theimages [i].getAttribute ("height")/2);
		theimages [i].setAttribute ("width", theimages [i].getAttribute ("width")/2);
	}
}

var x, Term, Def;	//031119
function showdef (term, def)
{
    Term = term;
    Def = def;
    x=window.open ('/mweb/definition.htm','mwebdef',
            'height=200,resizable,scrollbars,width=350,screenX=100,screenY=50,left=100,top=50');
    setTimeout ("writedef ()", 300);
}

function writedef ()
{
    //loops allow page time to load
    var t, d;

    //031119 NN7 just hangs
    while (!t)
        t = x.document.getElementById ("termspan");
    while (!d)
        d = x.document.getElementById ("defspan");

    t.innerHTML = Term;
    d.innerHTML = Def;

    x.focus ();
}

function termpopup (trmindex, gallery)
{
	//do not reset CurrentTermIndex

       	var docnode = TheTerms [trmindex].getElementsByTagName ("document") [0];
	if (docnode) 
	{
		var docfilename = docnode.getElementsByTagName ("filename") [0].firstChild.data;
		var docpath;

	    	//have to see if folder node exists before getting firstChild
	    	if (docnode.getElementsByTagName ("folder") [0])
    		{
			var docfolder = docnode.getElementsByTagName ("folder") [0].firstChild.data;
			docpath = "/mweb/" + docfolder + "/" + docfilename;
	    	}
    		else
			docpath = "/mweb/" + docfilename;
	}
		
	var x = window.open (docpath, 'popup', '');
	x.focus ();
}


function tnclick (key)
{
	document.getElementById('docspan').innerHTML = "";
	document.getElementById('dataspan').style.left = '21%'; 
	document.getElementById('dataspan').style.width = '79%'; 

	CurrentObjectKey = key;

	loadxml ("/mwebxml/mwebxml.exe?request=record&key=" + key, makerecord);
}
