/*  These functions are used to access the XML files stored
in the data subdirectory.  
 */
 
 /*  -------------------------------------------------------------------
      Debug is only used as I can't find a good javascript debugger!
	  OK I have MS script editor for IE now, but Mozilla has it's own bugs...
    -------------------------------------------------------------------
*/
 
var testing_script = false;  /* Beware 'debug' is a keyword in firefox! */
function scrawl (something)
{
	if (testing_script)
	   document.write(" "+something);
}
/*  -------------------------------------------------------------------
      Make the first character in a string Upper case, i.e. string->String 
    -------------------------------------------------------------------
*/
function capitalize (string)
{
	 var first = string.slice(0,1); 
     return(first.toUpperCase()+string.slice(1));
}
   
/*  -------------------------------------------------------------------
	follow goes to the html path given in menuChooser
	This is used by the drop down Form menu for prime navigation
    -------------------------------------------------------------------
*/

function follow(placeToGoTo) 
{
   var newURL=document.getElementById(placeToGoTo).value;
   scrawl (newURL);
   window.location=newURL;  // Change the URL, there may be parameters now
}


function OldFollow(placeToGoTo) 
{
   var newURL=document.getElementById(placeToGoTo).value;
   var hash = newURL.search("#");  // Check if a parameter is passed

   scrawl (newURL);
   if (hash < 0)  //  No parameters given
	{
	scrawl ("is a new URL"); 
	window.location=newURL;  // if URL is current, don't reload 
	}
   else
      if (document.URL.search(newURL.slice(0,hash)) < 0)  // new URL?	
	{	
	scrawl(newURL.slice(0,hash));
	window.location=newURL;  // Change the URL anyway, there may be parameters now
	}
      else	
	{
	window.location=newURL;  // Change the URL anyway, there are parameters now
	window.location.reload(); // Browsers 'optimize' by not reloading the current page
	}

}
/*  -------------------------------------------------------------------
Used to self reference and reload with a new parameter
    -------------------------------------------------------------------
*/
function goTo (added_parameter)  
{
  var myURL = window.location; // Inside a frame so not document.location
  var offset = myURL.search("#");
  if (offset > 0) // A # is in the URL from a previous parameter 
     myURL = myURL.slice(0, offset);  // Remove the old parameter 
  scrawl (myURL);
/*  window.location.replace(myURL+"#"+added_parameter);
  window.location.reload();
*/
}

/*  -------------------------------------------------------------------
      loadXML loads an XML file, the basic access to all XML data 
    -------------------------------------------------------------------
*/
function loadXML(dname) 
{
try //Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async=false;
  xmlDoc.load("data/"+dname+".xml");
  return(xmlDoc);
  }
catch(e)
  {
  try //Firefox, Mozilla, Opera, etc.
    {
    xmlDoc=document.implementation.createDocument("","",null);
    xmlDoc.async=false;
    xmlDoc.load("data/"+dname+".xml");
    return(xmlDoc);
    }
  catch(e) 
  {
  alert(e.message)
  return(null);
  }
  }
}

/*  -------------------------------------------------------------------
      The writeHTML function is mostly a stub to take <>s out of the code. 
    -------------------------------------------------------------------
*/
function writeHTML (tag_type)
{
   document.write("<"+tag_type+">");
}   


/*  -------------------------------------------------------------------
      The wrapHTML function writes a string to the screen
      between opening and closing HTML tags as specified. 
    -------------------------------------------------------------------
 */
function wrapHTML (tag_type, contents)
{
   document.write("<"+tag_type+">",contents,"</"+tag_type+">");
}

/*  -------------------------------------------------------------------
      The ItemLink function writes an HTNL link to item.php
		The two parameters are passed as a Query argument in the URL
    -------------------------------------------------------------------
 */
function itemLink (link_name, link_value)
{
	if (link_value == "No" || link_value == "Unknown")	
		document.write("&nbsp;");   // replace Unknown or No with a space
	else
	   document.write("<a href='Item.php?"+link_name+"="+link_value+"'>"+link_value+"</a>");
}
/*  -------------------------------------------------------------------
      The writeLink function write a string to the screen
      between opening and closing anchor HTML tags as specified.
	  If the page is the same as starting, it gets reloaded
    -------------------------------------------------------------------
 */
function writeLink (link_name, link_value)
{
	if (link_value == "No" || link_value == "Unknown")	
		document.write("&nbsp;");   // replace Unknown or No with a space
	else
	  document.write("<a href='"+link_name+".php?query="+link_value+"'>"+capitalize(link_value)+"</a>");
}

/*  -------------------------------------------------------------------
      One exception to normal links is that Inventories just say Yes
      between opening and closing anchor HTML tags. 
    -------------------------------------------------------------------
 */ 
function writeInventoryLink (link_value)
{
  document.write("<a href='Inventory.php?query="+link_value+"'>");
  document.write("Yes</a>");
}
/*  -------------------------------------------------------------------
      Draw a screenshot file or picture to the screen 
    -------------------------------------------------------------------
 */ 
function screenshot (place_value, subdir)
{
  document.write("<img src='data/screenshots/"+subdir+"/"+place_value+".jpg'>");
}
 
/*  -------------------------------------------------------------------
      Take a node and list all node element names and values  
    -------------------------------------------------------------------
 */
function listNode (subNode, subName)
{
	if (subNode != null) 
	{
		var y = subNode.childNodes.length;
		var tmp, i;
     	scrawl (y);
     	if (y>0)
      	{
      		wrapHTML("h5", subName); 
      		for (i=0; i<y; i++)
      		{
				tmp = subNode.childNodes[i];
				if (tmp.nodeType == 1)  // Only print elements
				{
					document.write(capitalize(tmp.nodeName)+" : ");
					if (tmp.nodeName == "quest")
						writeLink ("Quest", tmp.childNodes[0].nodeValue);
					else		
						document.write(tmp.childNodes[0].nodeValue); 
					document.write("<br />");
				}
      		}
		}
   	}
}

/*  -------------------------------------------------------------------
      showTable draws the starting HTML for a data table into the document 
      First of three functions to draw an XML table, see 
      showRow and endTable below.
    -------------------------------------------------------------------
*/

function showTable (table_name, item_node)
{
	document.write("<table border='1'>");
	wrapHTML("caption", table_name);
	//  Write header
	document.write("<thead><tr>");
	tmp = item_node.childNodes;
	var cols = 0;
	for (var j=0; j<tmp.length ; j++)
	   	{
		if (tmp[j].nodeType==1)
			{
			if (tmp[j].nodeName == "where" || tmp[j].nodeName == "vendor")
				break;   //  Don't expand beyond "where" or "vendor"
		    else
				{
				wrapHTML("th", capitalize(tmp[j].nodeName));
				cols++;
				}
		    }  
	   	};
	document.write("</tr></thead>");

	document.write("<tfoot>");
	document.write("<tr><td colspan='"+cols+"' align='center'>End of ",table_name," table</td></tr>");
	document.write("</tfoot>");
}

/*  -------------------------------------------------------------------
      Draws the HTML for one row in a data table, most elements are links 
    -------------------------------------------------------------------
*/

function showRow (data)
{
	writeHTML("tr");
	var tmp = data.childNodes;
	var name="none";
	for (var j=0; j<tmp.length ; j++)
		{  // Loop through all childNode Elements
		if (tmp[j].nodeType==1) // An element, not an attribute
			{   // Special cases
			if (tmp[j].nodeName=="vendor" || tmp[j].nodeName=="where") // Cut row short here
			   break;	
			else   
				{
				var datastring = tmp[j].childNodes[0].nodeValue;
				var stringtype = tmp[j].nodeName;
		    	if (name == "none")
					name=datastring;  // First in the row is the item name
				writeHTML("td");
				if (stringtype=="clothing" || stringtype=="ingredient" || stringtype=="valuable"
				  || stringtype=="armor"   || stringtype=="weapon"     || stringtype=="book"
				  || stringtype=="alchemy" || stringtype=="potion"	   || stringtype=="spell"
				  || stringtype=="object"  || stringtype=="opponent"   || stringtype=="person")
					itemLink(stringtype, datastring);
				else if (stringtype=="covering" || stringtype=="cover" || stringtype=="trainer"
						 || stringtype=="quest" || stringtype=="level")
				    writeLink(capitalize(stringtype), datastring);
				else if (stringtype=="inventory" && datastring=="Yes")	
 					writeInventoryLink(name); //  Replace the link name with a simple "yes"
				else if (stringtype=="scroll") 
					itemLink("Spell", datastring); // Switching from Scroll to Spell
            	else if (stringtype=="location")   // Location reads better than Place
 			   		writeLink("Place", datastring);
			    else if (stringtype=="supplies")
					{
					var type = tmp[j].attributes.getNamedItem("type");
                    if (type == null)
						document.write(datastring);
 					else
						itemLink(type.nodeValue, datastring);
					}
				else 
					document.write(datastring);  // Bland entries that are not links
				
				
            	writeHTML("/td");
				}
			}
		}
	writeHTML("/tr");
}
// End of showRow
/*  -------------------------------------------------------------------
      location Table draws the starting HTML for a data table
      This is a two element array using the Where elements 
      First of three functions to draw a location table, see 
      locationRow and endTable below.
    -------------------------------------------------------------------
*/

function locationTable (table_name)
{
	document.write("<table class='location' border='1'>");
	wrapHTML("caption", table_name);
	//  Write header
	document.write("<thead><tr>");
	wrapHTML ("th", "Location");
	wrapHTML ("th", "Detail");
	document.write("</tr></thead>");

	document.write("<tfoot>");
	document.write("<tr><td colspan='4' align='center'>End of location table</td></tr>");
	document.write("</tfoot>");
}
/*  -------------------------------------------------------------------
      Draws the table row HTML for location information on an object/item 
    -------------------------------------------------------------------
*/

function locationRow (data)
{
	tmp = data.childNodes;
	for (var j=0; j<tmp.length ; j++)
		{  // Loop through all childNode Elements, looking for "where"
		if (tmp[j].nodeType==1 && tmp[j].nodeName=="where") // An element, not attribute
			{
			var datastring = tmp[j].childNodes[0].nodeValue;
			var detail = tmp[j].attributes.getNamedItem("detail");
			writeHTML("tr");
			writeHTML("td");
            writeLink("Place", datastring);
			writeHTML("/td");
		    writeHTML("td");
			if (detail != null)
            	document.write(detail.nodeValue);
			else
				document.write("&nbsp;");
			writeHTML("/td");
			writeHTML("/tr");
			}
		};
	writeHTML("/tr");
}
// End of showRow
/*  -------------------------------------------------------------------
      vendorTable draws the starting HTML for a data table
      This is a two element array using the vendor elements 
      First of three functions to draw a location table, see 
      locationRow and endTable below.
    -------------------------------------------------------------------
*/

function vendorTable (table_name)
{
	
	document.write("<table class='vendor' border='1'>");
	wrapHTML("caption", table_name);
	//  Write header
	document.write("<thead><tr>");
	wrapHTML ("th", "Vendors");
	wrapHTML ("th", "Comment");
	document.write("</tr></thead>");

	document.write("<tfoot>");
	document.write("<tr><td colspan='4' align='center'>End of vendor table</td></tr>");
	document.write("</tfoot>");
}
/*  -------------------------------------------------------------------
      Draws the table row HTML for location information on an object/item 
    -------------------------------------------------------------------
*/

function vendorRow (data)
{
	tmp = data.childNodes;
	for (var j=0; j<tmp.length ; j++)
		{  // Loop through all childNode Elements, looking for "where"
		if (tmp[j].nodeType==1 && tmp[j].nodeName=="vendor") // An element, not attribute
			{
			var datastring = tmp[j].childNodes[0].nodeValue;
			var detail = tmp[j].attributes.getNamedItem("detail");
			writeHTML("tr");
			writeHTML("td");
            itemLink("person", datastring);
			writeHTML("/td");
		    writeHTML("td");
			if (detail != null)
              document.write(detail.nodeValue);
			else
			  document.write("&nbsp;");
			writeHTML("/td");
			writeHTML("/tr");
			}
		}
	writeHTML("/tr");
}
// End of showRow
/*  -------------------------------------------------------------------
      Completes and closes a table in the document 
    -------------------------------------------------------------------
*/ 
function endTable ()
{
  document.write("</table><br />");
		
}
/*  ------------------------------------------------------------------- 
      The searchFile looks through an XML file for the parameters given
    -------------------------------------------------------------------
*/
function locate_items (mySubject, myElement, myString)
{   //  Look in mySubject.xml for <myElement>myString</myElement>
    //  Return all relevant items that meet the criteria
    //  Best method is find all items, delete wrong ones, return the array 
    scrawl ("Loading...");
    var xmlDoc = loadXML(mySubject);
	scrawl ("...Done");
    var items = xmlDoc.getElementsByTagName("item");
	var i, j, finds, lose;
	scrawl (" for "+items.length+" items.");
	for (i = items.length-1; i>=0; i--)  // Loop for each item
		{
		// We do this backwards to delete from the tail of the list
		// removeChild in Firefox will cause the head of the list to collapse down!
		finds = items[i].getElementsByTagName(myElement);  //  All the myElement entries
		scrawl("cols="+finds.length);
		lose = true;  //  Whether to delete an item or not
		for (j=0; j<finds.length; j++)
			{  //  Loop again for multiple rows, e.g Vendors and Where
			if (finds[j].childNodes[0].nodeValue == myString)
			   {
			   lose = false;
			   scrawl("keeping node "+i);
			   }
			}
		if (lose)
	  		xmlDoc.documentElement.removeChild(items[i]); // Wipe out unwanted Items
		}
	return (xmlDoc);
}

function listItems (database, matchName, matchValue) 
{
	var reducedDoc = locate_items (database, matchName, matchValue);
	var items = reducedDoc.getElementsByTagName("item"); 
	var instock, tmp, i, j;
	if (items.length>0)
  	{  
  		wrapHTML("h5", capitalize(database)+"s include:");
  		writeHTML("ul");
  		for (i=0;i<items.length;i++)
     		{
	 		writeHTML("li");
			tmp = items[i].getElementsByTagName(database);
     		itemLink(database, tmp[0].childNodes[0].nodeValue); 
			
			if (matchName == "vendor" || matchName == "where") // Special cases, number attribute 
			   {
				tmp = items[i].getElementsByTagName(matchName);
				if (tmp != null)  // Then we have a vendor entry
					{
					scrawl (tmp.length);
					instock = "0";
					for (j=0;j<tmp.length; j++)
						{
						scrawl (tmp[j].childNodes[0].nodeValue);
						if (tmp[j].childNodes[0].nodeValue == matchValue)  // My vendor!
							{
							instock = tmp[j].attributes.getNamedItem("number");
							if (instock != null && instock.nodeValue != "0" && instock.nodeValue != "1")
								document.write (" * "+instock.nodeValue);
							}
						}
					}
				}
			writeHTML("/li");
			
			}
			
		writeHTML("/ul"); 
	}
	else
	  wrapHTML("h5", "No "+capitalize(database)+"s");
}

function showComment (node)
{
    var comment = node.attributes.getNamedItem("comment");
	if (comment != null)
	    wrapHTML ("p", comment.nodeValue);
}
function commentary(xmlDoc)
{
	wrapHTML("p", xmlDoc.getElementsByTagName("comment")[0].childNodes[0].nodeValue);
}
// End of file