// Global functions
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}
String.prototype.colontrim = function() {
	return this.replace(/:?$/,"");
}

function getElem(el){
// Use globally in place of 'document.getElementById(el)'
	if (typeof(el) != "string") {return el;}
	if (document.getElementById) {el=document.getElementById(el);}
	else if (document.all) {el=document.all[el];}
	else {el = null;}
return el;
}

// --------------------------------------------------------------------
// getElementsByClassName()
// Written by Jonathan Snook, snook-dot-ca/jonathan
// Add-ons by Robert Nyman, robertnyman-dot-com
// Can be called multiple ways:
//  Get all 'a' elements with the 'info-links' class within a document:
//    getElementsByClassName(document, "a", "info-links");
//  Get all 'div' elements with a 'col' class within an element with a 'container' id:
//    getElementsByClassName(document.getElementById("container"), "div", "col"); 
//  Get all elements with a 'click-me' class within a document:
//    getElementsByClassName(document, "*", "click-me"); 
// --------------------------------------------------------------------
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/-/g, "\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
} // End of getElementsByClassName()

// end Global functions

//***********************************************
function checkSSL() {
// Looks for an id="nonSSL" - if found, URL is changed from
// secure to unsecure. This shouldn't affect My Account cookie.
// User remains logged in but won't be using SSL on pages that
// don't need it.
var bodyID = getElem("nonSSL");
var newPg;
	if (!bodyID) {}
	else {
	var pageURL = new String(document.location);
		if (pageURL.indexOf("https://odyssey.aurora.lib.co.us:443") != -1) { 
		newPg = pageURL.replace(/https:\/\/odyssey.aurora.lib.co.us:443/,"http:\/\/odyssey.aurora.lib.co.us"); 
		document.location = newPg;
		}
		else {}
	}
}

/****************************************************************
 * random_pic()
 * Random image generator (not a slideshow). Replaced the
 * Ultimate Fade-In Slideshow on 1-15-09, which was ~150 lines of 
 * code and not as cross-browser compatible as this.
 * Randomly selects the upper-left image on every page from an array 
 * of 7 branch photos.
****************************************************************/
function random_pic() {
var img_name = new Array("/screens/images/home_cen.gif", "/screens/images/home_hof.gif",
"/screens/images/home_chp.gif", "/screens/images/home_ilf.gif", "/screens/images/home_mvl.gif", 
"/screens/images/home_mlk.gif", "/screens/images/home_tlr.gif");
var l = img_name.length;
var rnd_no = Math.floor(l*Math.random());
document.apl_img.src = img_name[rnd_no];
}
// end random_pic();

// *************************************************************
// togTopic() - Toggles the visibility of Topic Guide subcategories.
function togTopic(objID,tog) {
var togID = getElem(objID);
var onoff = getElem(tog);
togID.style.display = (togID.style.display != "none" ? "none" : "");
onoff.innerHTML = (onoff.innerHTML != '+' ? '+' : '-');
onoff.style.paddingLeft = (onoff.innerHTML == '-') ? '2px' : '1px';
onoff.style.paddingRight = (onoff.innerHTML == '-') ? '2px' : '1px';
}
	
// ***********************************************************
function checkifLogged() {
// Determines whether a patron is logged in.
var loggedIn = getElem("loggedin");
var logExist = (!loggedIn) ? false : true;
return logExist;
}

// *******************************
// chgSrchAct - changes form action in the toplogo search form
// based on which tab is selected.
function chgSrchAct() {
var topsearchForm = document.topSearch;
var tabs = document.topSearchTabs;
var siteTab = tabs.topSrchRad[0];
var catTab = tabs.topSrchRad[1];
//var theLang = isSpanish();
if (siteTab.checked == true) { }
else if (catTab.checked == true) {
		topsearchForm.action = '/search/X';
		topsearchForm.method = 'get';
		topsearchForm.elements[0].name = 'SEARCH';
		topsearchForm.elements[1].value = 'R';
		topsearchForm.elements[1].name = 'SORT';
		topsearchForm.elements[2].value = '2';
		topsearchForm.elements[2].name = 'searchscope';
}
return true;
}

// ***********************************************************
// changeSearch(ontab)
// In toplogo, changes the style of links to tabs. Necessary for
// chgSrchAct() to work properly.
function changeSearch(ontab) {
var catTab = getElem('toplogoCatLink');
var siteTab = getElem('toplogoSiteLink');
var srchform = document.topSearch;
	if (!srchform) {}
	if (ontab == 'cat') {
		catTab.className = "toplogoOn";
		catTab.parentNode.className = "toplogoSrchOn";
		siteTab.className = "toplogoOff";
		siteTab.parentNode.className = "toplogoSrchOff";
	}
	if (ontab == 'site') {
		catTab.className = "toplogoOff";
		catTab.parentNode.className = "toplogoSrchOff";
		siteTab.className = "toplogoOn";
		siteTab.parentNode.className = "toplogoSrchOn";
	}
	else {}
}

function switchTab(ontab,offtab) {
var myform = document.topSearch;
var butOn = getElem(ontab);
var butOff = getElem(offtab);
	if (butOff.className != "topLabelOff") {
		butOff.className = "topLabelOff";
		butOff.parentNode.className = "";
		butOff.style.color = "#666";
		butOff.setAttribute('onmouseover','this.style.color=\'#000\'');
		butOff.setAttribute('onmouseout','this.style.color=\'#666\'');
		butOn.className = "topLabelOn";
		butOn.parentNode.className = "toplogospan";
		butOn.style.color = "#000";
		butOn.setAttribute('onmouseover','');
		butOn.setAttribute('onmouseout','');
		myform.elements[0].focus();
	}
	else {}
}

// ****************************************************************
// * submitenter(myfield,e,func)                                  *
// * If Enter key is pressed instead of clicking the Submit       *
// * button on the toplogo form, the form will still be submitted *
// * properly (by calling chgSrchAct()), above.                   *
// ****************************************************************
function submitenter(myfield,e,func) {
var keycode;
	if (window.event) {
		keycode = window.event.keyCode;
	}
	else if (e) {
		keycode = e.which;
	}
	else return true;

	if (keycode == 13) {
		func();
	return false;
	}
	else return true;
} // end submitenter();

// ****************************************************************
function showTheseEvts(keyname,brName) {
// Used on the Events page to toggle visibility by branch.
var evtContain = getElem("allEvtsHere");
var evtdivs = evtContain.getElementsByTagName("div");
	if (evtdivs.length == 0) {}
	else {
		var keyDivs = getElementsByClassName(evtContain,'b','evtLocKey')
		var specDivs = getElementsByClassName(evtContain,'b',keyname);
		if (specDivs.length == 0) { 
			if (keyname == "evtLocAll") {
				alert("There are no events taking place at " + brName + ". Please select a specific branch.");
			}
			else {
				alert("There are no events taking place at " + brName + ". Please select another branch.");
			}
		}
		else {
			for (var j=0; j<keyDivs.length; j++) {
				keyDivs[j].parentNode.style.display = "none";
				if (brName != "Central Library") {
					var comps = getElem('loadComp');
					if (!comps){}
					else { comps.className = "hidden"; }
				}
				if (brName != "Hoffman Heights") {
					var compsH = getElem('loadCompHOF');
					if (!compsH){}
					else { compsH.className = "hidden"; } 
				}
			}
			for (var i=0; i<specDivs.length; i++) {
				specDivs[i].parentNode.style.display = "block";
			}
		}
	}
}

// Cleans up the form on the Advanced Search page.
function cleanAdvSrch() {
	var advT = getElem('advSrchTable');
	var advEl = advT.getElementsByTagName('span');
	var sortID = getElem("advSort");
	for (var i=0; i<advEl.length; i++) {
		advTD = advEl[i].getElementsByTagName("td");
		advTD[0].className = "advSrchLabel";
		advTD[1].className = "advSrchInput";
		if (sortID && sortID.firstChild.nodeType == 3) {
			sortID.firstChild.nodeValue = "";
		}
		else {}
	}
}

// -------------------------------------------------------------------
// Ajax XML Ticker (txt file source)
// Author: Dynamic Drive (dynamicdrive-dot-com)
// -------------------------------------------------------------------
//////////// No need to edit beyond here //////////////
function createAjaxObj(){
var httprequest = false;
	if (window.XMLHttpRequest){ // if Mozilla, Safari etc
		httprequest = new XMLHttpRequest();
		if (httprequest.overrideMimeType)
			httprequest.overrideMimeType('text/xml');
	}
	else if (window.ActiveXObject){ // if IE
		try {
			httprequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e){
			try {
				httprequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){
			}
		}
	}
return httprequest;
}

// -------------------------------------------------------------------
// Main Ajax Ticker Object function
// ajax_ticker(xmlfile, divId, divClass, delay, optionalfadeornot)
// -------------------------------------------------------------------

function ajax_ticker(xmlfile, divId, divClass, delay, fadeornot){
this.xmlfile=xmlfile //Variable pointing to the local ticker xml file (txt)
this.tickerid=divId //ID of ticker div to display information
this.delay=delay //Delay between msg change, in milliseconds.
this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over ticker (and pause it if it is)
this.pointer=0
this.opacitystring=(typeof fadeornot!="undefined")? "width: 98%; filter:progid:DXImageTransform.Microsoft.alpha(opacity=100); -moz-opacity: 1" : ""
if (this.opacitystring!="") this.delay+=500 //add 1/2 sec to account for fade effect, if enabled
this.opacitysetting=0.2 //Opacity value when reset. Internal use.
this.messages=[] //Arrays to hold each message of ticker
this.ajaxobj=createAjaxObj()
document.write('<div id="'+divId+'" class="'+divClass+'"><div style="'+this.opacitystring+'">Getting events...</div></div>')
this.getXMLfile()
}

// -------------------------------------------------------------------
// getXMLfile()- Use Ajax to fetch xml file (txt)
// -------------------------------------------------------------------

ajax_ticker.prototype.getXMLfile = function() {
	if (this.ajaxobj) {
		var instanceOfTicker = this;
		var url = this.xmlfile+"?bustcache="+new Date().getTime();
		this.ajaxobj.onreadystatechange = function() {
			instanceOfTicker.initialize();
		}
		this.ajaxobj.open('GET', url, true);
		this.ajaxobj.send(null);
	}
}

// -------------------------------------------------------------------
// initialize()- Initialize ticker method.
// -Gets contents of xml file and parse it using JavaScript DOM methods 
// -------------------------------------------------------------------

ajax_ticker.prototype.initialize=function(){ 
if (this.ajaxobj.readyState == 4) { //if request of file completed
  if (this.ajaxobj.status==200 || window.location.href.indexOf("http")==-1) { //if request was successful
  this.contentdiv=document.getElementById(this.tickerid).firstChild //div of inner content that holds the messages
  var xmldata=this.ajaxobj.responseText;
  this.contentdiv.style.display="none";
  this.contentdiv.innerHTML=xmldata;
    if (this.contentdiv.getElementsByTagName("div").length==0){ //if no messages were found
    this.contentdiv.innerHTML="<b>Error</b> loading events!";
    return
    }
  var instanceOfTicker=this
  document.getElementById(this.tickerid).onmouseover=function(){instanceOfTicker.mouseoverBol=1}
  document.getElementById(this.tickerid).onmouseout=function(){instanceOfTicker.mouseoverBol=0}
//modification by ajw
  var expireDate = getElementsByClassName(document,"*","message");
  var todayDate = getDate('rev');
//End modification
    if (window.attachEvent)  //Clean up loose references in IE
    window.attachEvent("onunload", function(){instanceOfTicker.contentdiv=instanceOfTicker.ajaxobj=null})
//Cycle through XML object and store each message inside array
      for (var i=0; i<this.contentdiv.getElementsByTagName("div").length; i++){
//modification by ajw
        var expireIdName = this.contentdiv.getElementsByTagName("div")[i].id;
        var activateId = expireIdName.substr(3,10); // reveal only 'activate' date
//		var thisYear = todayDate.slice(6); // isolate today's 4-digit year;
//		var actYear = activateId.slice(6,10); // isolate activation's 4-digit year;
//		var expYear = expireIdName.slice(22); // isolate expiration's 4-digit year;
        var validId = expireIdName.slice(16); // reveal only 'expire' date
        var regExTest = new RegExp("(\\s)*(message)(\\s)*");
        var theClasses = this.contentdiv.getElementsByTagName("div")[i].className;
//        if (theClasses.match(regExTest) && ((((actYear < thisYear) || (activateId <= todayDate)) && validId >= todayDate) || thisYear < expYear)) {
        if (theClasses.match(regExTest) && activateId <= todayDate && validId >= todayDate) {
//end modification
//        if (regExTest(this.contentdiv.getElementsByTagName("div")[i].className) && activateId <= todayDate && validId >= todayDate) {
//modification by ajw to limit number of chars in the event window
//		var evtConcat;
//			if (this.contentdiv.getElementsByTagName("div")[i].innerHTML.length > 380) {
//			evtConcat = this.contentdiv.getElementsByTagName("div")[i].innerHTML.slice(0,380) + '... <a href="/screens/programs/events.html">more &#187;</a>';
//			}
//			else {
//			evtConcat = this.contentdiv.getElementsByTagName("div")[i].innerHTML;
//			}
//		this.messages[this.messages.length] = evtConcat;
//end modification
        this.messages[this.messages.length]=this.contentdiv.getElementsByTagName("div")[i].innerHTML;
        }
      }
    this.contentdiv.innerHTML="";
    this.contentdiv.style.display="block";
    this.rotatemsg();
    }
  }
}

// -------------------------------------------------------------------
// rotatemsg()- Rotate through ticker messages and displays them
// -------------------------------------------------------------------

ajax_ticker.prototype.rotatemsg=function(){
var instanceOfTicker=this
if (this.mouseoverBol==1) //if mouse is currently over ticker, do nothing (pause it)
setTimeout(function(){instanceOfTicker.rotatemsg()}, 100)
else{ //else, construct item, show and rotate it!
this.fadetransition("reset") //FADE EFFECT- RESET OPACITY
this.contentdiv.innerHTML=this.messages[this.pointer]
this.fadetimer1=setInterval(function(){instanceOfTicker.fadetransition('up', 'fadetimer1')}, 100) //FADE EFFECT- PLAY IT
this.pointer=(this.pointer<this.messages.length - 1)? this.pointer + 1 : 0
setTimeout(function(){instanceOfTicker.rotatemsg()}, this.delay) //update container periodically
}
}

// -------------------------------------------------------------------
// fadetransition()- cross browser fade method for IE5.5+ and Mozilla/Firefox
// -------------------------------------------------------------------

ajax_ticker.prototype.fadetransition=function(fadetype, timerid){
var contentdiv = this.contentdiv;
if (fadetype == "reset")
this.opacitysetting=0.2;
if (contentdiv.filters && contentdiv.filters[0]){
if (typeof contentdiv.filters[0].opacity=="number") //IE6+
contentdiv.filters[0].opacity=this.opacitysetting*100
else //IE 5.5
contentdiv.style.filter="alpha(opacity="+this.opacitysetting*100+")"
}
else if (typeof contentdiv.style.MozOpacity!="undefined" && this.opacitystring!=""){
contentdiv.style.MozOpacity=this.opacitysetting;
}
else
this.opacitysetting=1;
if (fadetype=="up")
this.opacitysetting+=0.1;
if (fadetype=="up" && this.opacitysetting>=1)
clearInterval(this[timerid]);
}
// End of ajax_ticker script.
 

// *******************************************************************************
function getDate(dir) {
// Retrieves and formats today's date. If dir="rev", format is yyyy-mm-dd. Otherwise,
// format is mm-dd-yyyy.
   var now         = new Date();
   var monthnumber = now.getMonth();
   var monthname   = monthnumber + 1;
   var monthday    = now.getDate();
   var year        = now.getYear();
   if(year < 2000) { year = year + 1900; }
   if(monthday < 10) { monthday = '0' + monthday; }
   if(monthname < 10) { monthname = '0' + monthname; }
   var dateString;
   if (dir == 'rev') { dateString = year + '-' + monthname + '-' + monthday; }
   else { dateString = monthname + '-' + monthday + '-' + year; }
   return dateString;
} // End of getDate()

/**
 * expireThis()
 * Puts getElementsByClassName() and getDate() together to activate and
 * expire (ie, show and hide) block-level elements. Uses reverse date (2008-01-01). */
function expireThis(strClassName) {
var expDate = getElementsByClassName(document,"*",strClassName);
if (expDate.length == 0) {return;}
var todayDate = getDate('rev');
	for (i=0; i<expDate.length; i++) { // For elements where className == strClassName
		var expIdName = expDate[i].id;
		var expTag = expDate[i].tagName;
		var actId = expIdName.substr(3,10); // reveal only the 'activate' date;
		var validId = expIdName.slice(16); // reveal only the 'expire' date;
/** The element id contains the activate date (as the string 'act<date>') and expire
 * date (as the string 'exp<date>'). E.g., an element that should activate on Jul. 7, 2006
 * and expire on Aug. 2, 2006 would have id="act2006-07-07exp2006-08-02". The id
 * value cannot just be the date string or contain '/', because valid XHTML doesn't
 * allow an id to begin with a numeral.
 * If the element's activate date is on or before today AND its expire date is on or
 * after today, change the element's display property to 'block' (unless it's a table row) */
		if (actId <= todayDate && validId >= todayDate) {
			if (expTag == "TR") { expDate[i].style.display = ""; }
			else { expDate[i].style.display = "block"; }
//			expDate[i].className.replace(/expireMe/, "expireMe message");
		}
/** But if the activate date is on or before today AND its expire date is also on or
 * before today, OR if the activate date is after today, hide the element. */
		else if ((actId <= todayDate && validId < todayDate) || (actId > todayDate)) {
			expDate[i].style.display = "none";
		}
	}	
} // End of expireThis()

// ********************************************************************************
function showEvents() {
// Designed for the events calendar - uses getElementsByClassName() to dynamically
// change which events display depending on the form criteria chosen by the user.
var age = document.calSelect.agelist.options[document.calSelect.agelist.selectedIndex];
var branch = document.calSelect.branchlist.options[document.calSelect.branchlist.selectedIndex];
var everyCl = getElementsByClassName(document.getElementById("calWeek"), "div", "*");
 for (i=0; i<everyCl.length; i++) {
  everyCl[i].style.display = "none";
  var regExBr = new RegExp("(^|\\s)" + branch.id + "(\\s|$)");
  var regExAg = new RegExp("(^|\\s)" + age.id + "(\\s|$)");
  var classSlice = everyCl[i].className;
   if (branch.index > 0 && age.index > 0 && classSlice.match(regExBr) && classSlice.match(regExAg)) {
    everyCl[i].style.display = "block";
   }
   else if ((branch.index == 0 || age.index == 0) && (classSlice.match(regExBr) || classSlice.match(regExAg))) {
    everyCl[i].style.display = "block";
   }
   else if (branch.index == 0 && age.index > 0 && classSlice.match(regExAg)) {
    everyCl[i].style.display = "block";
   }
   else if (branch.index > 0 && age.index == 0 && classSlice.match(regExBr)) {
    everyCl[i].style.display = "block";
   }
   else if (branch.index == 0 && age.index == 0) {
    everyCl[i].style.display = "block";
   }
   else { }
 }
}

// ********************************************************************************
function showBranch() {
// Designed for the calendar of events - dynamically creates the calendar header
// based on the form criteria chosen by the user.
var optBr = document.calSelect.branchlist.options;
var optAg = document.calSelect.agelist.options;
var selBranch = optBr[document.calSelect.branchlist.selectedIndex];
var selAge = optAg[document.calSelect.agelist.selectedIndex];
	if (document.getElementById) {
		x = document.getElementById('branchNames');
		x.innerHTML = '';
		x.innerHTML = selBranch.value + " - " + selAge.value;
	}
	else if (document.all) {
		x = document.all['branchNames'];
		x.innerHTML = selBranch.value + " - " + selAge.value;
	}
} // End showBranch

// ********************************************************************************
function checkDay() {
// Compares today's day with calendar days; shades out days before today.
  	var weektab = getElem("calWeek");
	var weekdays = weektab.getElementsByTagName("td");
	var todaydate = getDate();
	var todayDay = todaydate.slice(3,5);
	var monthURL = new String(document.location);
	for (var i=0; i<weekdays.length; i++) {
		if (monthURL.indexOf('calendar.html') == -1 || weekdays[i].id == "" || weekdays[i].className == "monthdayFill") {}
		else if (weekdays[i].id.charAt(0) == "d") {
			var dayID = weekdays[i].id.slice(1);
			if (dayID < todayDay){
				weekdays[i].style.background = "#eee";
			}
		}
		else {}
	}
}

//***************************************************************
function hideMil() {
// 'Hides' the III branding on mainmenu.html and opacmenu.html by 
// changing the text color to the same as the background (currently #fff).
var theSpans = document.getElementsByTagName("span");
var lastSpan = theSpans.length - 1;
theSpans[lastSpan].style.display = "none";
} // end hideMil()

/*********************************
 * insert_rr_terms()
 * Inserts the search terms in the RightResult header next to the relevancy ranking.
*********************************/
function insert_rr_terms() {
// Assign a className to style the user's terms in the header;
var rrClass = "strong-em";

// If you also want to put the user's terms in the browser title bar, change these 3 variables;
var chgTitle = 1; // Off by default; change to '1' to turn it on;
var lib_or_cat_name = "Aurora Public Library - search results for "; // This is your library or catalog name, and should match whatever currently appears in your browser's title bar;
var title_suff = "" // This text will appear in the title bar after the user's terms;

// No need to edit beyond here;
if (!document.getElementsByName('searcharg')[0]) {return;}
var rrForm = document.getElementsByName('searcharg')[0];
var termArr = new Array("rrTerm1","rrTerm2","rrTerm3","rrTerm4","rrTerm5");
	for (var i=0; i<3; i++) {
		var termID = document.getElementById(termArr[i]);
		if (!termID) {}
		else {
			termID.innerHTML = rrForm.value;
			termID.className = rrClass;
		}
	}
	for (var i=3; i<termArr.length; i++) {
		var termID = document.getElementById(termArr[i]);
		if (!termID) {}
		else {
			newval = rrForm.value.replace(/^\s+|\s+$/g,"");
			newval = newval.replace(/\s/g," AND ");
			termID.innerHTML = newval;
			termID.className = rrClass;
		}
	}
if (chgTitle == 1) { document.title = lib_or_cat_name + "'" + rrForm.value + "'" + title_suff; }
}
// end insert_rr_terms();