/**
 * searchLinks.js
 * Nathan Rogers (nrogers@library.wisc.edu)
 * 2006-08-30
 *
 * When added to a subcollection page, if the search links are given the
 * id 'searchLink' this will append a query string containing the
 * subcollection ID
 */
 function getSubcollectionIdentifier() 
 {
  var metaTags = document.getElementsByTagName("meta");
  
  /**
    * This code assumes you are using the Identifire field.  For using the
    * DC.title field see below
    */
  for (i=0; i < metaTags.length; i++) 
  {
    if (metaTags[i].getAttribute("name") == 'DC.Identifier') 
    {
      contentAttribute = metaTags[i].getAttribute("content");
    }
  }
  
  subcollectionPattern = "1711\.dl/(.*)";
  subcollectionExpression = new RegExp(subcollectionPattern);
  results = subcollectionExpression.exec(contentAttribute);

  if (null == results) 

  {
    return "";
  } 
  else 
  {
    return results[1];
  }
}

function getSubcollectionTitle() 

{
  var metaTags = document.getElementsByTagName("meta");

  for (i=0; i < metaTags.length; i++) 

  {
    if (metaTags[i].getAttribute("name") == 'DC.Title') 
    {
      subcollection = metaTags[i].getAttribute("content");
    }
  }
  
  /** Shorten the title to 50 characters if it is too long */
  if (subcollection.length > 50) 
  {
    subcollection = subcollection.substring(0, 50);
  }
  
  /** Now URL Encode it */
  subcollection = escape(subcollection.replace(/ /g, "+"));
  
  if (null == subcollection) 
  
  {
    return "";
  } 
  else 
  {
    return subcollection;
  }
}

function appendSubcollection(nameProperty, subcollectionId) 

{
  var navigationDivElement = document.getElementById("navigationContainer");
  var anchorTags = navigationDivElement.getElementsByTagName("a");
  
  for (i = 0; i < anchorTags.length; i++) 
  
  {
    hrefAttribute = anchorTags[i].getAttribute("href");
    classAttribute = anchorTags[i].className;
    
   if ((null == classAttribute) ||
        ("searchLink" != classAttribute)) 
        {
      continue;
    }
   
    /**
     * This part should only be reached if the class attribute is set.  Now you 
     * can safely append the subcollection id
     */
     var targetURL = anchorTags[i].getAttribute("href");
     
     if (-1 == targetURL.lastIndexOf("?")) 
     
     {
      targetURL = targetURL + "?subcollection=" + subcollectionId;
     } 
     else 
     {
      targetURL = targetURL + "&subcollection=" + subcollectionId;
    }
    
    anchorTags[i].setAttribute("href", targetURL);
    
  }
}

window.onload = function() 

{
  //subcollectionId = getSubcollectionIdentifier();
  subcollectionId = getSubcollectionTitle();
  
  /**
   * The next thing to do is locate all links with an id of 'searchLink' and
   * append a queryString to their href property
   */
  if ("" != subcollectionId) 
  {
    appendSubcollection("searchLink", subcollectionId);
  }
}
