// Object for making requests back to the server.
var request = null;

// Get an element's value.
// inElement   - parent element.
// inTag       - tag of desired elements.
// inPos       - possition in elements.
// inDefault   - default value.
function getElementData (inElement, inTag, inPos, inDefault)
{
  var elements = null;
  var element  = null;
  var child    = null;
  var data     = null;

  if (inElement != null)
  {
    elements = inElement.getElementsByTagName(inTag);
    if (elements != null)
    {
      element = elements[inPos];
      if (element != null)
      {
        child = element.firstChild;
        if (child != null)
        {
          data = child.data
        }
      }
    }
  }
  if (data == null)
  {
    data = inDefault;
  }

  return data;
}

// Create the request object.
// Try different mechanisms to support various browsers.
// Store the object in a globally accessable object.
function createRequest()
{
  try
  {
    request = new XMLHttpRequest();
  }
  catch (trymicrosoft)
  {
    try
    {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (othermicrosoft)
    {
      try
      {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (failed)
      {
        request = null;
      }
    }
  }

  if (request == null)
  {
    alert("Error creating request object!");
  }
}

// Issue request to the server for the Gallery Index.  The function
// populateGalleryIndex_callback is called when the response is received.
// The index is displayed in the callback function, not here.
function populateGalleryIndex ()
{
  createRequest ();

  request.open("GET", "/medalsdb.php?cmd=getIndex", true);      // Initialize the request.
  request.onreadystatechange = populateGalleryIndex_callback;   // Set the callback function.
  request.send(null);                                           // Send the request to the server.
}

// Process the gallery index.  The XML is processed by the request object
// and it's parts are retrieved by the getElementsByTagName function.
function populateGalleryIndex_callback()
{
  if (request.readyState == 4)     // The response from the server has completed.
  {
    if (request.status == 200)     // The server has responded with "success".
    {
      var results  = request.responseXML.getElementsByTagName("entry");   // Get all the "entry" elements from the response.
      var indexDiv = document.getElementById("galleryindex");             // Get the div element that holds the index.
      var entry    = null;                                                // A single entry from the results.

      for (var i=0; i<results.length; i++)                                // For each entry...
      {
        var label;       // Label to display for an entry.
        var type;        // The type of entry: "decade" lists ten year's worth of items.
                         //                    "localid" displayes the content of an already loaded item (by id).
        var galleryId;   // Unique identifier for the requested gallery.

        label = results[i].getElementsByTagName("label")[0].firstChild.data;
        type = results[i].getElementsByTagName("type")[0].firstChild.data;
        galleryId = results[i].getElementsByTagName("galleryid")[0].firstChild.data;

        entry = document.createElement("div");   // Create division for the index entry.
        entry.className = "galleryindexentry";   // Class for an index entry.
        entry.galleryId = galleryId;             // Set it's id.

        // Function to populate the gallery when the index item is selected.
        if (type == "decade")  // Populate a "decade" gallery.  Ten years worth of medals.
                               // The galleryId specifies the decade to be displayed.
        {
          entry.onclick = function () { populateGalleryByDecade(this.galleryId); };
        }
        else if (type == "localid")  // Populate the gallery from an already existing item.
        {
          entry.onclick = function () { populateGalleryByLocalId(this.galleryId); };
        }

        entry.appendChild(document.createTextNode(label)); // Add the label to the entry.

        indexDiv.appendChild(entry);                       // Add the new entry to the index.
      }
    }
  }
}

// Populate a gallery with an already existing item.
function populateGalleryByLocalId(inId)
{
  var galleryDiv = document.getElementById("gallerybody");  // The gallery division.
  var contentDiv = document.getElementById(inId);           // The new content to display.

  var displayDiv = contentDiv.cloneNode(true);              // Make a copy to work with.

  // Clear the current content of the gallery division.
  var curr = galleryDiv.childNodes;
  for (var i=curr.length-1; i>=0; i--)
  {
    galleryDiv.removeChild(curr[i]);
  }

  displayDiv.className = "displayedintrogallery";   // Make the new content visible.
  galleryDiv.appendChild(displayDiv);               // Add the new content to the gallery.
}

// Populate a gallery with a given decade's worth of items.
function populateGalleryByDecade(inDecade)
{
  createRequest ();   // Ensure the request object exists.

  request.open("GET", "/medalsdb.php?cmd=getDecade&dec=" + inDecade, true);  // Initialize the request.
  request.onreadystatechange = populateGallery_callback;                     // Set the callback function.
  request.send(null);                                                        // Send the request.
}

// Get the data for a given element assuming there is zero or one value for that element.
function getElement_single (inMedal, inElement)
{

//inParent.getElementsByTagName("scoppa")[0].firstChild.data;

  var allElements;
  var firstElement;
  var child;

  allElements = inMedal.getElementsByTagName("scoppa");
  if (typeof(allElements) == "undefined") return "";

  firstElement = allElements[0];
  if (typeof(firstElement) == "undefined") return "";

  child = firstElement.firstChild;
  if (child  == null) return "";
  
  return child.data;
}

// Process the response to populate the gallery.
function populateGallery_callback()
{
  if (request.readyState == 4)     // The response from the server has completed.
  {
    if (request.status == 200)     // The server has responded with "success".
    {
      var results    = request.responseXML.getElementsByTagName("medal");   // Get all the "medal" entries.
      var galleryDiv = document.getElementById("gallerybody");            // Get the gallery.
      var entry      = null;                                                // A single entry for this gallery.
      var entrybody  = null;
      var entrytr    = null;
      var imagecol   = null;
      var datacol    = null;
      var mintcol    = null

      var curr       = galleryDiv.childNodes;                                   // The current content of the gallery.

      var scoppa;      // Scoppa number for the medal.
      var issued;      // Year in which the medal was issued.
      var type;        // Type of medal: "pres" presidential medal.
      var name;        // Name of the president being honored on the medal.
      var number;      // The number of the presedent (first, second, ...).
      var images;      // Collection of images for this medal.
      var mintages;    // Collection of mintages for this medal.
      var image;       // A single image.
      var purpose;     // The reason a non-presidetial medal was issued.
      var thumbdiv;    // A div object to hold a thumbnail image.

      var mintagefield; // Field to display mintage data.

      // Clear the current content.
      for (var i=curr.length-1; i>=0; i--)
      {
        galleryDiv.removeChild(curr[i]);
      }

      for (var i=0; i<results.length; i++)      // For each medal.
      {
        // Get the fields common to all medals.
        scoppa   = getElement_single(results[i], "scoppa");
        issued   = results[i].getElementsByTagName("issued")[0].firstChild.data;
        type     = results[i].getElementsByTagName("type")[0].firstChild.data;
        images   = results[i].getElementsByTagName("images")[0].getElementsByTagName("image");
        mintages = results[i].getElementsByTagName("mintages")[0].getElementsByTagName("mintage");

        if (type == "pres")   // This is a presidential medal.
        {
          name   = results[i].getElementsByTagName("name")[0].firstChild.data;
          number = results[i].getElementsByTagName("number")[0].firstChild.data;
        }
        else                  // This is a non-presidential medal.
        {
          purpose = results[i].getElementsByTagName("purpose")[0].firstChild.data;
        }

        entry = document.createElement("table");   // Table for this entry.
        entry.className = "galleryentry";        // class for an entry.

        entrybody = document.createElement("tbody");
        entry.appendChild (entrybody);

        entryrow = document.createElement("tr");
        entrybody.appendChild (entryrow);

        imagecol = document.createElement("td");
        datacol  = document.createElement("td");
        mintcol  = document.createElement("td");

        imagecol.className = "galleryentrycolimage";
        datacol.className  = "galleryentrycoldata";
        mintcol.className  = "galleryentrycolmint";

        entryrow.appendChild (imagecol);
        entryrow.appendChild (datacol);
        entryrow.appendChild (mintcol);



        for (var j=0; j < images.length; j ++)   // For each image of this medal.
        {
          image = images[j];                     // Current image.

          obj = document.createElement("img");
          obj.setAttribute ("src", image.getElementsByTagName("thumb")[0].firstChild.data);  // URL for thumbnail image.
          obj.className = "gallerythumbimg";
          obj.fullfile = image.getElementsByTagName("file")[0].firstChild.data;  // URL to the full-size file.
          obj.onclick = function () { openWindow (this.fullfile); };             // function to call when this item is selected.

          imagecol.appendChild(obj);                    // Add this image to the gallery entry.
        }

        datacol.appendChild (createDataField (scoppa, type, issued, number, name, purpose));

        mintageField = createMintageField (mintages);
        if (mintageField != null)
        {
          mintcol.appendChild (mintageField);
        }

        flowobj = document.createElement("div");
        flowobj.className = "flowwrapper";

        flowobj.appendChild(entry);

        galleryDiv.appendChild(flowobj);       // Add the entry to the gallery.
      }
    }
  }
}

// Open a given URL in a new window.
function openWindow (inUrl, inName)
{
  var sizing = "height=500,width=500";
  var win = window.open(inUrl);

  if (win)
  {
    win.focus();
  }
  else
  {
    alert ("Could not open a new window to display this image.  Please turn off popup blocking.");
  }
}

// Create the data fields to display with a medal.
// inScoppa   - The Scoppa number of the medal.
// inType     - The type of medal: "pres" - presidential.
// inIssued   - The year the medal was issued.
// inNumber   - The number of the president's term (presidential medals only).
// inName     - The name of the prsident (presidential medals only).
// inPurpose  - The purpose of the medal (non-presidential medals only).
function createDataField (inScoppa, inType, inIssued, inNumber, inName, inPurpose)
{
  var div;
  var table;
  var tbody;

  // Create a table containing the relevant data fields.

  table = document.createElement("table");
  table.className = "gallerydatatable";

  tbody = document.createElement("tbody");
  table.appendChild(tbody);

  if (inScoppa != "")
  {
    tbody.appendChild(createDataRow ("Scoppa #", inScoppa));
  }

  if (inType == "pres")
  {
    tbody.appendChild(createDataRow ("Issued", inIssued + " (" + inNumber + ")"));
    tbody.appendChild(createDataRow ("Name",   inName));
  }
  else
  {
    tbody.appendChild(createDataRow ("Year Issued", inIssued));
    tbody.appendChild(createDataRow ("Purpose", inPurpose));
  }

  return table;
}

// Create the mintage fields to display with a medal.
// inMintages - Array of mintage figures.
function createMintageField (inMintages)
{
  var table;
  var tbody;
  var mintage
  var count;

  var material;
  var production;
  var comment;

  count = inMintages.length;

  if (count  > 0)
  {
    table = document.createElement("table");
    table.className = "gallerymintagetable";

    tbody = document.createElement("tbody");
    table.appendChild(tbody);

    for (var i=0; i<inMintages.length; i++)      // For each mintage
    {
      material   = inMintages[i].getElementsByTagName("material")[0].firstChild.data;
      production = inMintages[i].getElementsByTagName("production")[0].firstChild.data;
      comment    = getElementData (inMintages[i], "comment", 0, "");

      tbody.appendChild(createMintageRow (material, production, comment));
    }
  }

  return table;
}

// Create a row of data for the data fields of a given medal.
// inLabel - Label for the data field.
// inValue - Value for the data field.
function createDataRow(inLabel, inValue)
{
  var row;
  var col;
  var bold;

  row   = document.createElement("tr");
  col   = document.createElement("td");
  col.className = "galleryheadercol";
  bold = document.createElement("b");
  bold.appendChild(document.createTextNode (inLabel + ":"));
  col.appendChild(bold);
  row.appendChild(col);

  col   = document.createElement("td");
  col.className = "gallerydatacol";
  col.appendChild(document.createTextNode(inValue));
  row.appendChild(col);

  return row;
}


// Create a row of mintage data for the given medal.
// inLabel - Label for the data field.
// inValue - Value for the data field.
function createMintageRow(inMaterial, inProduction, inComment)
{
  var row;
  var col;

  row   = document.createElement("tr");

  col   = document.createElement("td");
  col.className = "gallerymintagecol";
  col.appendChild(document.createTextNode(inMaterial));
  row.appendChild(col);

  col   = document.createElement("td");
  col.className = "gallerymintagecol";
  col.appendChild(document.createTextNode(inProduction));
  row.appendChild(col);

  col   = document.createElement("td");
  col.className = "gallerymintagecol";
  col.appendChild(document.createTextNode(inComment));
  row.appendChild(col);

  return row;
}



