// 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(/:?$/,"");
}

// This function can be replaced by jQuery's $("#[id]")
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;
}

// This function can be replaced by jQuery's $(".[classname]")
// --------------------------------------------------------------------
// 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()

// Store the current URL as a string for later parsing;
var loc = document.location.href;
  
// 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.
//
// 10-12-09 - not sure this script is necessary anymore.
//var bodyID = getElem("nonSSL");
//var newPg;
	if ($("#nonSSL").length==0) {}
	else {
//	var pageURL = new String(document.location);
		if (loc.indexOf("https://odyssey.aurora.lib.co.us:443") != -1) { 
			document.location = loc.replace(/https:\/\/odyssey.aurora.lib.co.us:443/,"http:\/\/odyssey.aurora.lib.co.us"); 
		}
		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();

/**
 * injectHTML()
 * Insert random HTML elements from an array via Ajax.
 * @param {Object} dest - where to inject the content
 * @param {Object} url - where to get the content
 * @param {Object} els - which elements to randomize
 */
function injectHTML(dest,url,els) {
	$(dest).load(url,function(){
		var n = $(els).length;
		var rnd_no = Math.floor(n*Math.random());
		$(els).hide();
		$(els + ":eq(" + rnd_no + ")").show().css('padding','.333em');
	});
}

// *************************************************************
// togTopic() - Toggles the visibility of Topic Guide subcategories.
function togTopic(objID,tog) {
$("#"+objID).toggle();
var onoff = getElementById(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';
}
	
// ***********************************************************
// No longer used as of 6/5/09?
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();


// -------------------------------------------------------------------
// 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()


/** hideMil()
 * 'Hides' the III branding on mainmenu.html and opacmenu.html
*/
function hideMil() {
$("span:last").css('display','none');
}// end hideMil();
