/*
	GLOBAL.JS
	Contains global functions
*/

/* NOTE:
When working with global.js, function setAction should point to search3 on libwww3 and search on libwww - don't accidentally copy over to live server while pointed to search3. CP 11/10/06
*/

function daySuffix(d) {
	//returns the appropriate date suffix for the given day number. (3 = rd, 14 = th, 21 = st)
	//found here: http://www.frequency-decoder.com/2006/07/20/correctly-calculating-a-date-suffix
	d = String(d);
	return d.substr(-(Math.min(d.length, 2))) > 3 && d.substr(-(Math.min(d.length, 2))) < 21 ? "th" : ["th", "st", "nd", "rd", "th"][Math.min(Number(d)%10, 4)];
}

function Trim(inString) {
  	var retVal = "";
  	var start = 0;
  	while ((start < inString.length) && (inString.charAt(start) == ' ')) {
    	++start;
  	}
  	var end = inString.length;
  	while ((end > 0) && (inString.charAt(end - 1) == ' ')) {
    	--end;
  	}
  	retVal = inString.substring(start, end);
  	return retVal;
}


function IsNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;
   if (strString.length == 0) 
   //alert("Please enter a value.");
   return false;
   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
	//alert("Please enter a numeric value.");
   return blnResult;
   }
   
function IsLen(strString, len)
   //  check for length of a string	
   {
   var str = strString.value;
   if (str.length != len) {
	   alert("Entry does not contain the required "&len&" characters.");
	   return false;   
	   } 
	   else 	
	   {
		return true;   
		   }	   
   }
   
function IsFLPCardNum(CardNum)
   //  check for length of a string	
   { 
   if (!IsNumeric(CardNum)) { 
	   alert("Please enter a numeric value for the library card.");
	   return false; 
	}	
    else 	
	   {
		return true;   
		   }	   
   } 
        

function IsFLPPin(PinNum)
   //  check for length of a string	
   { 
    if (!IsNumeric(PinNum)) { 
	   alert("Please enter a numeric value for the PIN.");
	   return false; 
	}	
    else 	
	   {
		return true;   
		   }	   
   } 


function BrowserDetector() {
var ua = navigator.userAgent
// Defaults
  this.browser = "Unknown";
  this.platform = "Unknown";
  this.version = "";
  this.majorver = "";
  this.minorver = "";

  uaLen = ua.length;

// ##### Split into stuff before parens and stuff in parens
  var preparens = "";
  var parenthesized = "";

  i = ua.indexOf("(");
  if (i >= 0) {
    preparens = Trim(ua.substring(0,i));
        parenthesized = ua.substring(i+1, uaLen);
        j = parenthesized.indexOf(")");
        if (j >= 0) {
          parenthesized = parenthesized.substring(0, j);
        }
  }
  else {
    preparens = ua;
  }

// ##### First assume browser and version are in preparens
// ##### override later if we find them in the parenthesized stuff
  var browVer = preparens;

  var tokens = parenthesized.split(";");
  var token = "";
// # Now go through parenthesized tokens
  for (var i=0; i < tokens.length; i++) {
    token = Trim(tokens[i]);
        //## compatible - might want to reset from Netscape
        if (token == "compatible") {
          //## One might want to reset browVer to a null string
          //## here, but instead, we'll assume that if we don't
          //## find out otherwise, then it really is Mozilla
          //## (or whatever showed up before the parens).
        //## browser - try for Opera or IE
    }
        else if (token.indexOf("MSIE") >= 0) {
      browVer = token;
    }
    else if (token.indexOf("Opera") >= 0) {
      browVer = token;
    }
        //'## platform - try for X11, SunOS, Win, Mac, PPC
    else if ((token.indexOf("X11") >= 0) || (token.indexOf("SunOS") >= 0) ||
(token.indexOf("Linux") >= 0)) {
      this.platform = "Unix";
        }
    else if (token.indexOf("Win") >= 0) {
      this.platform = token;
        }
    else if ((token.indexOf("Mac") >= 0) || (token.indexOf("PPC") >= 0)) {
      this.platform = token;
        }
  }

  var msieIndex = browVer.indexOf("MSIE");
  if (msieIndex >= 0) {
    browVer = browVer.substring(msieIndex, browVer.length);
  }

  var leftover = "";
  if (browVer.substring(0, "Mozilla".length) == "Mozilla") {
    this.browser = "Netscape";
        leftover = browVer.substring("Mozilla".length+1, browVer.length);
  }
  else if (browVer.substring(0, "Lynx".length) == "Lynx") {
    this.browser = "Lynx";
        leftover = browVer.substring("Lynx".length+1, browVer.length);
  }
  else if (browVer.substring(0, "MSIE".length) == "MSIE") {
    this.browser = "Internet Explorer";
    leftover = browVer.substring("MSIE".length+1, browVer.length);
  }
  else if (browVer.substring(0, "Microsoft Internet Explorer".length) ==
"Microsoft Internet Explorer") {
    this.browser = "Internet Explorer"
        leftover = browVer.substring("Microsoft Internet Explorer".length+1,
browVer.length);
  }
  else if (browVer.substring(0, "Opera".length) == "Opera") {
    this.browser = "Opera"
    leftover = browVer.substring("Opera".length+1, browVer.length);
  }

  leftover = Trim(leftover);

  // # Try to get version info out of leftover stuff
  i = leftover.indexOf(" ");
  if (i >= 0) {
    this.version = leftover.substring(0, i);
  }
  else
  {
    this.version = leftover;
  }
  j = this.version.indexOf(".");
  if (j >= 0) {
    this.majorver = this.version.substring(0,j);
    this.minorver = this.version.substring(j+1, this.version.length);
  }
  else {
    this.majorver = this.version;
  }


} // function BrowserCap


/*------------------------------------------------------------
	Document Text Sizer- Copyright 2003 - Taewook Kang.  All rights reserved.
	Coded by: Taewook Kang (txkang.REMOVETHIS@hotmail.com)
	Web Site: http://txkang.com
	Script featured on Dynamic Drive (http://www.dynamicdrive.com)
	
	Please retain this copyright notice in the script.
	License is granted to user to reuse this code on 
	their own website if, and only if, 
	this entire copyright notice is included.
--------------------------------------------------------------*/

//Specify affected tags. Add or remove from list:
var tgs = new Array( 'div','td','tr');

//Specify spectrum of different font sizes:
var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
var startSz = 2;

function ts( trgt,inc ) {
	if (!document.getElementById) return
	var d = document,cEl = null,sz = startSz,i,j,cTags;
	
	sz += inc;
	if ( sz < 0 ) sz = 0;
	if ( sz > 6 ) sz = 6;
	startSz = sz;
		
	if ( !( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];

	cEl.style.fontSize = szs[ sz ];

	for ( i = 0 ; i < tgs.length ; i++ ) {
		cTags = cEl.getElementsByTagName( tgs[ i ] );
		for ( j = 0 ; j < cTags.length ; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
	}
}

// Clears text in form fields

 function doClear(theText) 
{
     if (theText.value == theText.defaultValue)
 {
         theText.value = ""
     }
 }
 
 // Checks or unchecks form checkboxes
 
 function SetAllCheckBoxes(FormName, FieldName, CheckValue){
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

 function SetAllCheckBoxesB(FormName, CheckValue){
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements;
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

//  Preload background images

image1 = new Image();
image1.src = "/images/global/bg_ask_on.gif";

image2 = new Image();
image2.src = "/images/global/bg_explore_on.gif";

image3 = new Image();
image3.src = "/images/global/bg_find_on.gif";


/*------------------------------------------------------------
	FLP Redesign -- 
	Display Top Nav bar Dynamically using client-side javascript
	e.g. DisplayTopNav ("About", 1)
		 DisplayTopNav ("Support", 0)
Modified by Feihong Yu 07/28/2005		 

--------------------------------------------------------------*/

function DisplayTopNav (tabname, highlight) 
  {
if (tabname == "Support") {
document.write('<td id=' + (highlight == 1 ? '"redtopnav"' : '"greytopnav"') + ' width="25%">');
document.write('<div id=' + (highlight == 1 ? '"rednav"' : '"greynav"') + ' width="90%" >');	
	}
else {
document.write('<td id=' + (highlight == 1 ? '"redrightnav"' : '"greyrightnav"') + ' width="25%">');
document.write('<div id=' + (highlight == 1 ? '"rednav"' : '"greynav"') + ' width="90%" >');			
}
	if (tabname == "About")
	{	highlight == 1 ? document.write('About the Library') : document.write('<a href="http://www.library.phila.gov/about/index.htm" target="_top">About the Library</a>'); }
	else if (tabname == "Find")
	{	highlight == 1 ? document.write('Find a Location') : document.write('<a href="http://libwww.library.phila.gov/branches/brnlist.cfm" target="_top">Find a Location</a>');}
	else if (tabname == "Programs")
	{	highlight == 1 ? document.write('Programs & Services') : document.write('<a href="http://www.library.phila.gov/libserv/index.htm" target="_top">Programs & Services</a>');}
	else if (tabname == "Support")
	{	highlight == 1 ? document.write('Support the Library') : document.write('<a href="http://www.library.phila.gov/support/index.htm" target="_top">Support the Library</a>');}

		document.write('</div>');
		document.write('</td>');
  }


/* Function to generate Popup windows.
This function generates a new popup each time the user clicks on a link that activates this Fun. Because the windowname is different for each instance. 
If you want to limit the number of popUp windows (to only one), make the windowname a Constant.
*/

function FLPPopUpWindow(mylink, windowname)
{ var href;
if (typeof(mylink) == 'string')
   href=mylink;
else
   href=mylink.href;
FLPPopUp = window.open(href, windowname, 'location=yes,menubar,toolbar,status,height=520,width=740,menu,scrollbars,resizable,left=260,top=0');
FLPPopUp.focus();
return false;
}

function FLPPopUpWindowMax(aURL, aWinName){
   var wOpen;
   var sOptions;
   sOptions = 'status=yes,menubar=yes,scrollbars=yes,resizable=yes,toolbar=yes';
   sOptions = sOptions + ',width=' + (screen.availWidth - 11).toString();
   sOptions = sOptions + ',height=' + (screen.availHeight - 123).toString();
   sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';
   wOpen = window.open( '', aWinName, sOptions );
   wOpen.location = aURL;
   wOpen.focus();
   wOpen.moveTo( 1, 1 );
   wOpen.resizeTo( screen.availWidth, screen.availHeight );
   return wOpen;
}


function FLPPopUpNoResize(aURL, aWinName){
   var wOpen;
   var sOptions;
   sOptions = 'location=yes,menubar,toolbar,status,menu,scrollbars';
   sOptions = sOptions + ',width=' + (screen.availWidth - 100).toString();
   sOptions = sOptions + ',height=' + (screen.availHeight - 200).toString();
   sOptions = sOptions + ',screenX=0,screenY=0,left=0,top=0';
   wOpen = window.open( '', aWinName, sOptions );
   wOpen.location = aURL;
   wOpen.focus();
   wOpen.moveTo( 1, 1 );
   
   return wOpen;
}


function FLPPopUpWindowLarge(mylink, windowname)
{ var href;
if (typeof(mylink) == 'string')
   href=mylink;
else
   href=mylink.href;
FLPPopUp = window.open(href, windowname, 'location=yes,menubar,toolbar,status,height=500,width=500,menu,scrollbars,resizable,left=0,top=0');
FLPPopUp.focus();
return false;
}

function FLPPopUpPic(mylink, windowname){
/*	var href;
	if (typeof(mylink) == 'string')
	   href=mylink;
	else
	   href=mylink.href;
	FLPPopUp = window.open(href, windowname, 'location=yes,menubar,toolbar,status,height=200,width=200,menu,scrollbars,resizable,left=260,top=0');
	FLPPopUp.focus();
	return false;
*/
	FLPPopup = window.open(mylink, windowname, "resizable=1,HEIGHT=200,WIDTH=200");
	FLPPopup.focus();
	return false;
}

function CloseFLPPopUp()
{
if (typeof(FLPPopUp) != "undefined") {FLPPopUp.close();}
}

/* Same as above, but smaller window
*/
function FLPTinyPop(mylink, windowname)
{ var href;
if (typeof(mylink) == 'string')
   href=mylink;
else
   href=mylink.href;
FLPPopUp = window.open(href, windowname, 'location=yes,menubar,toolbar,status,height=300,width=400,menu,scrollbars,resizable,left=260,top=0');
FLPPopUp.focus();
return false;
}

/* Functions for the search box */

function validateSearch(which) {
 beforeSearchFormSubmitSimple(which);
 var frm = document.forms[which];
 var tmp = frm.keyword.value.replace(/ /gi, "");
 if ( tmp == '' ) {
  alert("Please enter your search term(s).")
  frm.keyword.focus();
  return false;
 }
 
 return setAction(this);
}

function trim(s){
	if(s.length>0){
		if(s.charAt(0)==' '){
			s=s.substr(1,s.length-1);
			s=trim(s)
		}
		if(s.charAt(s.length-1)==' '){
			s=s.substr(0,s.length-1);
			s=trim(s)
		}
	}
	return s;
}

function escapeQuot(s){
	//s = s.replace(/"/g,"%22");
	return s;
}

function beforeSearchFormSubmitSimple(which){
	var f = document.forms[which];
	var query = f.keyword.value;
	query = trim(query);
	f.keyword.value = escapeQuot(query);
	return;
}

// Changed this function 7/23/07 - previously, the first kform.method was "post", the kw.name was "keyword", and the action was 'http://search3.library.phila.gov/results.cfm'
// Simple search box will now feed results directly to AquaBrowser interface, while allowing for continued function of "site search only" option

function setAction() {
	if (document.QuickSearch.searchType.value == "aquabrowser") {
		kw = document.getElementById("keyword");
		kform = document.getElementById("QuickSearch");
		kform.method="get"
		kw.name = "q"
		document.QuickSearch.action = 'http://know.library.phila.gov:9000'
	}
	else {
		if (document.QuickSearch.searchTech.checked == false) {
			kw = document.getElementById("keyword");
			kform = document.getElementById("QuickSearch");
			kform.method="post";// "get" 
			kw.name = "keyword";// "q" 
			document.QuickSearch.action = 'http://search.library.phila.gov/results.cfm';// 'http://know2.library.phila.gov' 
		}
		else {
			kw = document.getElementById("keyword");
			kform = document.getElementById("QuickSearch");
			kform.method="get";
			kw.name = "q";
			document.QuickSearch.action = 'http://find.library.phila.gov/search';
		}
	}
	return true;
}

function click(which) {
	if (document.QuickSearch.searchTech.checked == true) {
    document.QuickSearch.searchTech.checked = false;
	}
	else{
    document.QuickSearch.searchTech.checked = true;
	}
}