
// 09/05/2003 C.W.F.
// Mod 12/2006 - add font tests C.W.F. FootPrint 8644

function cleanSearchTerms(inSearchTerms)
	// Strip all search control chars from an input string.
 	{
	// Get rid of any phrase search ("), boolean start/end chars, and proximity operators 
	var workString="";
	var inProximityState=false;
	var lastAdd="";
	var thisAdd="";
	var charsToSkip='"' + "'()&!;";
	var digits="012345456789";
	var thisChar = "";
	
	len = inSearchTerms.length;
	for (p=0; p < len; p++)
		{
		thisChar = inSearchTerms.charAt(p);
		thisAdd = " ";
		if (thisChar == "+")
			if (inProximityState)
				inProximityState = false;
				
			else
				{
				nextProx = inSearchTerms.indexOf("+", p+1);
				for (q=p+1; q < nextProx; q++)
					{
					thisChar = inSearchTerms.charAt(q);
					inProximityState = (digits.indexOf(thisChar) > -1);
					if (!inProximityState)
						break;
					}
				}
		else if (inProximityState)
			{
			//  Ignore all proximity characters
			}
		else if (charsToSkip.indexOf(thisChar) == -1)
			{
			//  A valid search character.
			thisAdd = thisChar;
			}
		if (thisAdd == " " && lastAdd == " ")
			{
			//  No consecutive spaces.
			}
		else if (thisAdd == " " && p == len - 1)
			{
			//  No trailing spaces.
			}
		else
			{
	    lastAdd = thisAdd;
			workString += thisAdd;
			}
	  }
	return workString;
  }


// Function to zap the stylesheet info, and print a plain version of a window.
function printPlainWindow()
{
document.styleSheets[0].disabled=true;
window.print();
setTimeout("document.styleSheets[0].disabled=false",2000);
}

// This code, used by the table column sort function,  is necessary for browsers that don't reflect
// the DOM constants (like IE!).
if (document.ELEMENT_NODE == null)
  {
  document.ELEMENT_NODE = 1;
  document.TEXT_NODE = 3;
  }


// Used by the table column sort function
function compareValues(v1, v2)
  {
  var f1, f2;

  // If the values are numeric, convert them to floats.

  f1 = parseFloat(v1);
  f2 = parseFloat(v2);
  if (!isNaN(f1) && !isNaN(f2))
  {
  v1 = f1;
  v2 = f2;
  }

  // Compare the two values.
  if (v1 == v2) return 0;
  if (v1 > v2)  return 1;
  return -1;
  }

// Regular expressions for normalizing white space.
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");

// used primarily by the table column sort function
function normalizeString(s)
  {
  s = s.replace(whtSpMult, " ");  // Collapse any multiple white space.
  s = s.replace(whtSpEnds, "");   // Remove leading or trailing white space.
  return s;
  }

// Function to get the text value from a table row node - used by the table column sort function
function getTextValue(el)
  {
  var i;
  var s;

  // Find and concatenate the values of all text nodes contained
  // within the element.
  s = "";
  for (i = 0; i < el.childNodes.length; i++)
  if (el.childNodes[i].nodeType == document.TEXT_NODE)
    s += el.childNodes[i].nodeValue;
  else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&
       el.childNodes[i].tagName == "BR")
    s += " ";
  else
    // Use recursion to get text within sub-elements.
    s += getTextValue(el.childNodes[i]);
//  s = s.toLowerCase();
  return normalizeString(s);
  }


// Function to enable sorting of a selected table column. The table body section is normally passed in.
function sortTable(tableID,col,col2)
  {
  window.status="Sorting...";
  // Get the table section to sort.
  var tblEl = document.getElementById(tableID);

  // Set the table display style to "none" - necessary for Netscape 6 
  // browsers.
  var oldDsply = tblEl.style.display;
  tblEl.style.display = "none";

  // Sort the rows based on the content of the specified column

  var tmpEl;
  var i, j;
  var minVal, minIdx;
  var testVal;
  var cmp;
  var cmp1;
  var cmp2;

  for (i = 0; i < tblEl.rows.length - 1; i++)
  {
  minIdx = i;
  minVal = getTextValue(tblEl.rows[i].cells[col]);
	minVal = minVal.toLowerCase();
  // Search the rows that follow the current one for a smaller value.
  for (j = i + 1; j < tblEl.rows.length; j++)
	  {
    testVal = getTextValue(tblEl.rows[j].cells[col]);
	  testVal = testVal.toLowerCase();
    cmp = compareValues(minVal, testVal);

//  If those values are equal, and if a second column is set, sort by the second column.
    if (col2 != null)
	  {
	  if (cmp == 0 && col != 1)
		  {
      //  cmp = compareValues(getTextValue(tblEl.rows[minIdx].cells[col2]),
      //          getTextValue(tblEl.rows[j].cells[col2]));
		  cmp1 = getTextValue(tblEl.rows[minIdx].cells[col2]);
		  cmp1 = cmp1.toLowerCase();
		  cmp2 = getTextValue(tblEl.rows[j].cells[col2]);
		  cmp2 = cmp2.toLowerCase();
		  cmp = compareValues(cmp1,cmp2);
      }
    }

    // If this row has a smaller value than the current minimum,
    // remember its position and update the current minimum value.
    if (cmp > 0)
	  {
    minIdx = j;
    minVal = testVal;
    }
    }

  // By now, we have the row with the smallest value. Remove it from
  // the table and insert it before the current row.
  if (minIdx > i)
	  {
    tmpEl = tblEl.removeChild(tblEl.rows[minIdx]);
    tblEl.insertBefore(tmpEl, tblEl.rows[i]);
    }
  }

  // Restore the table's display style.
  tblEl.style.display = oldDsply;
  window.status = "Sort complete"
  return false;
  }

  // prototypes to enable Mozilla etc to utilise the IE innerText 
  var isIE = (window.navigator.userAgent.indexOf("MSIE") > 0);
  if (! isIE)
  {
  HTMLElement.prototype.__defineGetter__("innerText",
        function () { return(this.textContent); });
  HTMLElement.prototype.__defineSetter__("innerText",
        function (txt) { this.textContent = txt; });
  }

function getOS()
  {
  var plat = navigator.platform.toUpperCase();
  var is_mac = (plat.indexOf("MAC") != -1);
  var is_win = (plat.indexOf("WIN") != -1);
  var is_unix = (plat.indexOf("UNIX") != -1) || (plat.indexOf("LINUX") != -1);

  if (is_mac) return "MAC";
  else if (is_win) return "WIN";
  else if (is_unix) return "UNIX";
  else return "UNKNOWN";
	}	


// Font detection
function testForFontsAvail(testFontString, specialFontLangs, typeSiteVirtual)
  {
  var installHelpReqd = false;

	var testFontsArray = testFontString.split("~");
  var testFontLangs = specialFontLangs.split("~");

  var testFontSizes = new Array();
  var testFontList = new Array();
  var testFontURLs = new Array();

  var thisFontName = "";
  var thisFontFileName ="";
  
  var tfl = testFontsArray.length;

  for (var a=0; tfl > a; a++)
    {
    if (testFontsArray[a].toUpperCase().indexOf("NO FONT ASSIGNED") != -1)
		  {
			alert("No font has been assigned for language " + testFontLangs[a] + ".\n Please advise the Library.\n(Some data may not display correctly if an appropriate font is not installed on your workstation)");
			continue;
			}
		var thisFontArrayLine = testFontsArray[a].split(","); // see if there is more than one font for this language
    if (thisFontArrayLine.length == 1) // only one optional font for this language
      {
      thisFontName = "";
      var thisFontArrayLineSplit = thisFontArrayLine[0].split("^");
      thisFontName = thisFontArrayLineSplit[0];
      testFontList[a] = thisFontName;
      testFontSizes[a] = thisFontArrayLineSplit[3];
      testFontURLs[a] = thisFontArrayLineSplit[2];
      }
    if (thisFontArrayLine.length > 1) // More than one optional font
      {
      var multiCount = 0;
      thisFontName = "";
      testFontSizes[a] = "";
      testFontURLs[a] = "";
      while (multiCount < thisFontArrayLine.length)
        {
        var thisFontArrayLineSplit = thisFontArrayLine[multiCount].split("^");
        if (thisFontName.length > 0)
          {
          thisFontName = thisFontName + ", ";
          testFontSizes[a] = testFontSizes[a] + ",";
          testFontURLs[a] = testFontURLs[a] + ",";
          }
        thisFontName = thisFontName + thisFontArrayLineSplit[0]; 
        testFontSizes[a] = testFontSizes[a] + thisFontArrayLineSplit[3]; 
        testFontURLs[a] = testFontURLs[a] + thisFontArrayLineSplit[2];
        multiCount += 1;
        }
      testFontList[a] = thisFontName;
      }
    }

  detectTestFonts(testFontList);
  
  var tf = testFontList.length;
  var alertText = "";
  var alertTextHdr1 = "Some information uses the ";
  var alertTextHdr2 = "\nThe following suggested ";
  var alertTextHdr3 = "\nSome data may not display correctly. \n";
  var alertTextHdr4 = "may not be not installed on this machine. \n"
  var fontOrFonts = "font ";
  var languageOrLanguages = " language";
  var isAre = "is ";
  var noFontCount = 0;
  var missingFonts = "";
  var missingLanguages = "";

  for (var n=0; tf > n; n++)
    {
    if (testFontsArray[n].toUpperCase().indexOf("NO FONT ASSIGNED") != -1) continue;
		if (testFontResult[n] == "no")
      {
      missingFonts = missingFonts + testFontList[n] + " (" + testFontLangs[n] + ") \n";
      if (missingLanguages.length > 0) missingLanguages = missingLanguages + ", ";
      missingLanguages = missingLanguages + testFontLangs[n];
      noFontCount += 1;
      }
    }
  if (noFontCount > 0)
    { 
    if (noFontCount > 1)
      {
      fontOrFonts = " fonts "; isAre = "are "; languageOrLanguages = " languages";
      }
    //alertText = alertTextHdr1 + missingLanguages + languageOrLanguages + "." + alertTextHdr3 + alertTextHdr2 + fontOrFonts + isAre + alertTextHdr4 + missingFonts;
    alertText = alertTextHdr1 + missingLanguages + languageOrLanguages + "." + alertTextHdr3 + alertTextHdr2 + fontOrFonts + alertTextHdr4 + missingFonts;
    alert(alertText);
    }

  var dlAns;
  // See if they want to download the font(s)
  installHelpReqd = false;
	for (var n=0; tf > n; n++)
    {
    if (testFontsArray[n].toUpperCase().indexOf("NO FONT ASSIGNED") != -1) continue;
		if (testFontResult[n] == "no")
      {
      if (testFontList[n].indexOf(",") == -1) // If there is only one optional font offered
        {
        dlAns = confirm("Would you like to download the font (size " + String(Math.round(parseInt(testFontSizes[n])/1000)) + " kb) \nfor " + testFontList[n] + " (" + testFontLangs[n] + ") ?\n\n(NOTE: Save the file with any prefix such as 'WIN_' removed.\nYou will need to install the font after downloading)");
        if (dlAns)
          {
          installHelpReqd = true;
				  //var dlWin = window.open(testFontURLs[n], 'Download', 'width=100,height=100,innerWidth=100,innerHeight=100,left=99999,top=99999');
					var location = window.location;
					window.location = testFontURLs[n];
					
					}
        }
      if (testFontList[n].indexOf(",") != -1) // more than one font offered - loop through them
        {
        // create the sub-arrays
        var multiOptionFonts = testFontList[n].split(",");
        var multiOptionSizes = testFontSizes[n].split(",");
        var multiOptionURLs = testFontURLs[n].split(",");
        var muFontsLength = multiOptionFonts.length;

        for (var m=0; muFontsLength > m; m++)
          {
					dlAns = confirm("Would you like to download the font (size " + String(Math.round(parseInt(multiOptionSizes[m])/1000)) + " kb) \nfor " + multiOptionFonts[m] + " (" + testFontLangs[n] + ") ?\n\n(NOTE: Save the file with any prefix such as 'WIN_' removed.\nYou will need to install the font after downloading)");
          if (dlAns)
            {
            installHelpReqd = true;
						if (window.showModalDialog) 
						  {
						  var dlWin = window.open(multiOptionURLs[m],'Download','width=100,height=100,innerWidth=100,innerHeight=100,left=9999,top=9999');
							}
					  else
 						  var dlWin = window.open(multiOptionURLs[m],'Download','width=100,height=100,innerWidth=100,innerHeight=100,left=9999,top=9999,modal=yes');
						}
          }
        }
      }
    }
  // see if font install help is required
  if (installHelpReqd) fontInstallHelp(typeSiteVirtual);
	}

function fontInstallHelp(typeSiteVirtualIn)
  {
  dlAns = confirm("Would you like some help on font installation after the download?");
	if (dlAns)
	  {
    var currentLocation = window.location;
    var thisOS = getOS();
	  var thisInterval = "";
	  if (thisOS == "WIN")
      openLinkWindow(typeSiteVirtualIn + '/includes/winFontHelp.htm');
	  else if (thisOS == "MAC")
      openLinkWindow(typeSiteVirtualIn + '/includes/macFontHelp.htm');
		else if (thisOS == "UNIX") 
      openLinkWindow(typeSiteVirtualIn + '/includes/unixFontHelp.htm');
		}
  }

function doNothing() {return;};

var testString = "i";
var detectedResponse = "yes";
var undetectedResponse = "no";

function detectTestFonts(testFontList)
  {
  if(document.createElement)
	  {
//    testFontList = new Array(); // set up by caller
    var hasFonts = true;
    try {hasFonts = getTestFontList();}
    catch(e) {hasFonts = false;}
    if(hasFonts)
		  {
      placeTestFontSpans(testFontList);
//      if(testFontResult[0] == undetectedResponse) {alert("changeSmallFonts()"); changeSmallFonts();}  // Optional.
      }
    }
  }

function placeTestFontSpans(testFontList)
  {
  if((testFontList.length) > 0)
	  {
    var undefined;
    var tf = testFontList.length;
    testfontdiv = document.getElementById("theTestFontDiv");
    if(testfontdiv)
		  {
      testFontSpan = new Array();
      testFontChar = new Array();
      testMonoSpan = document.createElement("span");
      testMonoSpan.style.fontFamily = "monospace";
      testMonoChar = document.createTextNode(testString);
      testMonoSpan.appendChild(testMonoChar);
      testfontdiv.appendChild(testMonoSpan);
      testSerifSpan = document.createElement("span");
      testSerifSpan.style.fontFamily = "serif";
      testSerifChar = document.createTextNode(testString);
      testSerifSpan.appendChild(testSerifChar);
      testfontdiv.appendChild(testSerifSpan);
      for(var n=0; tf>n; n++)
			  {
        if(testFontList[n]==undefined) testFontList[n] = "";
        testFontSpan[n] = document.createElement("span");
        testFontSpan[n].style.fontFamily = testFontList[n] + ",monospace";
        testFontChar[n] = document.createTextNode(testString);
        testFontSpan[n].appendChild(testFontChar[n]);
        testFontSpan[tf+n] = document.createElement("span");
        testFontSpan[tf+n].style.fontFamily = testFontList[n] + ",serif";
        testFontChar[tf+n] = document.createTextNode(testString);
        testFontSpan[tf+n].appendChild(testFontChar[tf+n]);
        }
      testFontSpan[2*tf] = document.createElement("span");
      testFontSpan[2*tf].fontFamily = "monospace";
      testFontChar[2*tf] = document.createTextNode(testString);
      testFontSpan[2*tf].appendChild(testFontChar[2*tf]);
      for(var n=0; (2*tf)>=n; n++)
			  {
        testfontdiv.appendChild(testFontSpan[n]);
        }
      testfontdiv.style.display = "block";
      var referenceMonoResult = getXposition(testSerifSpan) - getXposition(testMonoSpan);
      var referenceSerifResult = getXposition(testFontSpan[0]) - getXposition(testSerifSpan);
      testFontResult = new Array();
      for(var n=0; tf>n; n++)
			  {
        var monoFontResult = getXposition(testFontSpan[n+1]) - getXposition(testFontSpan[n]);
        var serifFontResult = getXposition(testFontSpan[tf+n+1]) - getXposition(testFontSpan[tf+n]);
        var totalResult = (monoFontResult != referenceMonoResult) || (serifFontResult != referenceSerifResult);
        if(totalResult == true) testFontResult[n] = detectedResponse;
        else testFontResult[n] = undetectedResponse;
        }
      testfontdiv.style.display = "none"
      }
    }
  }

// functions getXposition() and getYposition() thanks to www.quirksmode.org

function getYposition(whichelement)
  {
  var ypos = 0;
  if (whichelement.offsetParent)
	  {
    while (whichelement.offsetParent)
		  {
      ypos += whichelement.offsetTop
      whichelement = whichelement.offsetParent;
      }
    }
  return ypos;
  }

function getXposition(whichelement)
  {
  var xpos = 0;
  if (whichelement.offsetParent)
	  {
    while (whichelement.offsetParent)
		  {
      xpos += whichelement.offsetLeft
      whichelement = whichelement.offsetParent;
      }
    }
  return xpos;
  }


function getTestFontList()
  {
/*
   testFontList[0] = "'Times New Roman, Times'";
   testFontList[1] = "'Times New Roman', Times";  // almost always present
   testFontList[2] = "Arial";
   testFontList[3] = "'MS Mincho', 'MS PMincho'";
   estFontList[4] = "'Geez Unicode'";
   testFontList[5] = "Tahoma";
*/
   
  var hasMoreFonts = true;
  try {hasMoreFonts = getMoreTestFontList();}
  catch(e) {hasMoreFonts = false;}
  if(hasMoreFonts) hasMoreFonts = getMoreTestFontList();
  return true;
  }
  
function writeCookie(cookieName, value1, expiryMinutes)
  {
  // set expiry date
  var d = new Date();
  d.setTime(d.getTime() + (expiryMinutes * 60 * 1000)); 
  var cd = d.toGMTString();
 
  var c = cookieName + "=" + value1 + ";expires=" + cd + ";";
  // write cookie
  document.cookie = c;
  }

function getCookie(Name)
  {
  var search = Name + "=";
  var returnvalue = "";
  if (document.cookie.length > 0)
    {
    offset = document.cookie.indexOf(search);
    // if cookie exists
    if (offset != -1)
      { 
      offset += search.length;
      // set index of beginning of value
      end = document.cookie.indexOf(";", offset);
      // set index of end of cookie value
      if (end == -1) end = document.cookie.length;
      returnvalue=unescape(document.cookie.substring(offset, end));
      }
    }
  return returnvalue;
  }  

function eraseCookie(Name)
  {
	writeCookie(Name, "", -1);
	}
	

// function to replace all instances of the given substring.
String.prototype.replaceAll = function( 
strTarget, // The substring to replace
strSubString // The string to replace with.
)
  {
  var strText = this;
  var intIndexOfMatch = strText.indexOf( strTarget );

  // Keep looping while an instance of the target string
  // still exists in the string.
  while (intIndexOfMatch != -1)
  {
  // Replace out the current instance.
  strText = strText.replace( strTarget, strSubString )

  // Get the index of any next matching substring.
  intIndexOfMatch = strText.indexOf( strTarget );
  }

  // Return the updated string with ALL the target strings
  // replaced out with the new substring.
  return( strText );
  }

// Function to  "write content into ID"
function WriteContentIntoID(id,content)
  {
  if(document.getElementById)
	  {
	  var idvar = document.getElementById(id);
	  idvar.innerHTML = '';
	  idvar.innerHTML = content;
	  }
  else if(document.all)
	  {
	  var idvar = document.all[id];
	  idvar.innerHTML = content;
	  }
  else if(document.layers)
	  {
	  var idvar = document.layers[id];
	  idvar.document.open();
	  idvar.document.write(content);
	  idvar.document.close();
	  }
  }


