// JavaScripts used throughout the site...

/* ----------------------------------------------------------------------
FormFocus
This function places the focus on a form field when a page loads
if it finds a field designated "inputFocusTarget"

Call using this code:
<body onload="FormFocus()"...
<input type="text" name="WHATEVER" id="inputFocusTarget"/>
*/
function FormFocus() {
	if(document) {
		if(document.getElementById) {
			if(document.getElementById("inputFocusTarget")) {
				document.getElementById("inputFocusTarget").focus();
			}
		}
	}
}

/* ----------------------------------------------------------------------
FlipFormVisibility
This function hides and unhides SELECT form items so that the menu will
appear properly.
*/
function FlipFormVisibility() {
	if(document.forms) {
		// Get all the form objects into an array.
		Item = new Array();
		for(i=0; i < document.forms.length; i++) {
			Item.push(document.forms[i]);
		}
		// Find all the childNodes of the form objects.
		for(i=0; i < Item.length; i++) {
			for(j=0; j < Item[i].childNodes.length; j++) {
				Item.push(Item[i].childNodes[j]);
			}
			// If the childNode is a SELECT field, hide/unhide it.
			if(Item[i].nodeName == 'SELECT') {
				if(Item[i].style.visibility == 'hidden') {
					Item[i].style.visibility = 'visible';
				} else {
					Item[i].style.visibility = 'hidden';
				}
			}
		}
	}
}
/* ----------------------------------------------------------------------
HighlightChanges
This function adds styles and functions to every form on the page, so
that when the user makes changes to the information the field that
was changed is highlighted.  When they submit to the same page,
the fields will return to their original color.

Useful on our editing pages where the form submits and displays
the information for editing again immediately, so that it is not
clear whether the information has been saved or not.
*/
function HighlightChanges() {
	if(document.forms) {
		// Get all the form objects into an array.
		Item = new Array();
		for(i=0; i < document.forms.length; i++) {
			Item.push(document.forms[i]);
		}
		// Find all the childNodes of the form objects.
		for(i=0; i < Item.length; i++) {
			for(j=0; j < Item[i].childNodes.length; j++) {
				Item.push(Item[i].childNodes[j]);
			}
			// Add styles and functions to textareas and text input boxes.
			if(Item[i].nodeName == 'TEXTAREA' ||
				(Item[i].nodeName == 'INPUT' && Item[i].type == 'text')) {

				Item[i].style.background = '#ffffff';
				Item[i].style.border = '1px solid #999999';
				Item[i].style.padding = '1px';

				if(Item[i].onkeyup == null) {
					Item[i].onkeyup=function() { this.style.background = '#ffff99'; }
				}
				if(Item[i].onchange == null) {
					Item[i].onchange=function() { this.style.background = '#ffff99'; }
				}
			}

			// Add styles and functions to drop down menus.
			if(Item[i].nodeName == 'SELECT') {
				Item[i].style.background = '#ffffff';
				Item[i].style.border = '1px solid #999999';
				Item[i].style.padding = '1px';

				if(Item[i].onchange == null) {
					Item[i].onchange=function() { this.style.background = '#ffff99'; }
				}
			}

			// Add functions to submit buttons.
			if(Item[i].nodeName == 'INPUT' && Item[i].type == 'submit') {
				if(Item[i].onclick == null) {
					Item[i].onclick=function() { this.value += ' . . .'; }
				}
			}
		}
	}
}


/* ----------------------------------------------------------------------
ReScroll
This function keeps a textarea in your form scrolled to the same place
even after submitting the form.  Useful for the Memex where you are
saving often and don't want to have to scroll back to where you were
after every save.

Use the following code to call this function:
<body onload="ReScroll()"...>
<textarea name="WHATEVER"></textarea>
<input type="hidden" name="WHATEVER_scrolltop" id="WHATEVER_scrolltop"
	value="<?php echo $_POST["WHATEVER_scrolltop"]; ?>"/>

The function must be called onload to work properly in Mozilla.
*/
function ReScroll() {
	if(document.forms) {
		// Get all the form objects into an array.
		Item = new Array();
		for(i=0; i < document.forms.length; i++) {
			Item.push(document.forms[i]);
		}
		// Find all the childNodes of the form objects.
		for(i=0; i < Item.length; i++) {
			for(j=0; j < Item[i].childNodes.length; j++) {
				Item.push(Item[i].childNodes[j]);
			}

			// Add re-scrolling functions to TEXTAREAs.
			if(Item[i].nodeName == 'TEXTAREA') {
				// Figure out how the rescroller field would be named.
				rescroller = Item[i].name + "_scrolltop";
				// If the rescroller field exists...
				if(document.getElementById(rescroller)) {
					// Set the scrolltop back to the rescroller value
					if(document.getElementById(rescroller).value > 0) {
						Item[i].scrollTop = document.getElementById(rescroller).value;
					}
					// When the scrolltop value changes add it to the field.
					// Mozilla doesn't support onscroll, use onblur instead
					Item[i].onblur=function() {
						document.getElementById(rescroller).value = this.scrollTop;
					}
				}
			}
		}
	}
}


/* ----------------------------------------------------------------------
ActivateSearchForm
This function shows or hides the search form in the page banner.

<a href="http://www.williams.edu/library/search/"
	onclick="return ActivateSearchForm()">SEARCH</a>

<form style="visibility:hidden" id="searchForm" method="get" action="http://www.williams.edu/library/search/">
	Search this site:<br/>
	<input id="searchField" type="text" name="s" size="14" maxlength="255"/>
	</form>
*/
function ActivateSearchForm() {
	// If the form exists...
	if(document && document.getElementById && document.getElementById("searchForm")) {

		// If the form field is visible
		if(document.getElementById("searchForm").style.visibility == "visible") {

			// If there is text in the form field, submit the form.
			if(document.getElementById("searchField") &&
				document.getElementById("searchField").value != "") {

				document.getElementById("searchForm").submit();
				return false;
			}

			// Otherwise, hide the form.
			document.getElementById("searchForm").style.visibility = "hidden";
			return false;

		}
		// If the form field is hidden
		else {
			// Make the form visible.
			document.getElementById("searchForm").style.visibility = "visible";
			// Put the focus on the form field.
			if(document.getElementById("searchField")) {
				document.getElementById("searchField").focus();
			}
			return false;
		}
	}
	// If the script couldn't find the form, return true and allow the user
	// to proceed to the search page.
	return true;
}

/* ----------------------------------------------------------------------
BounceTo
This function takes a link and sends it through a redirect page
in order to track the traffic on the site.

Here is a properly formatted link:

<a href="/library/staff/" onclick="BounceTo(this)">Staff</a>

In this case, the visit to /library/staff/ would be logged
and the user would be directed to the staff page seamlessly.
*/
function BounceTo(thisLink) {
	if(thisLink) {
		if(thisLink.href) {
			if(thisLink.href.indexOf('bounce.php') < 0) {
				thisLink.href =
					'http://librarydev.hamilton.edu/' + thisLink.href;
			}
		}
	}
	return true;
}


/* ----------------------------------------------------------------------
ShowTile
This function displays the contents of the site map in a dynamic pane.
One heading displays by default when the page loads, id=FindingInfoDummy
It should always be turned off when another Heading is clicked
*/

//Tile = first part of id name for selected item
var oldTile; // first part of id name for previously displayed item

function ShowTile(Tile) {

	if(document.getElementById(oldTile + 'Heading')) {
		document.getElementById(oldTile + 'Heading').className = "headingOff";
	}
	else
	{
		document.getElementById('FindingInfoHeadingDefault').style.visibility = 'hidden';
	}

	oldTile = Tile;

	document.getElementById('QuickPicksHeading').className = "defaultheadingOn";

	if(document.getElementById(Tile + 'Heading')) {
		document.getElementById('QuickPicksHeading').className = "defaultheadingOff";
		document.getElementById(Tile + 'Heading').className = "headingOn";
	}

	if(document.getElementById(Tile)) {
		document.getElementById("displayTile").innerHTML =
			document.getElementById(Tile).innerHTML;

		// Expire after 1 minute so they can see the pretty picture again.
		var exp = new Date();
		exp.setTime(exp.getTime() + (1*1000));
		SetCookie("Tile", Tile, exp);
	}
}

function LoadTile() {
	var Tile = GetCookie("Tile");
	ShowTile(Tile);
}

/*
E-journals Scripts
*/
function navigate(form) {
	var myindex=form.select1.selectedIndex
	if (form.select1.options[myindex].value != "0") {
		location=form.select1.options[myindex].value;
	}
}

function browse(form) {
	var myindex=form.select1.selectedIndex
	if (form.select1.options[myindex].value != "0") {
		location=form.select1.options[myindex].value;
	}
}

function search(form) {
	var myindex=form.select1.selectedIndex
	if (form.select1.options[myindex].value != "0") {
		location=form.select1.options[myindex].value;
	}
}
// End E-Journals Scripts




// Cookie Functions  ////////////////////  (:)

// Set the cookie.
// SetCookie('your_cookie_name', 'your_cookie_value', exp);

// Get the cookie.
// var someVariable = GetCookie('your_cookie_name');

var expDays = 30;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
//exp.setTime(exp.getTime() + (3*60*1000));


function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) { endstr = document.cookie.length; }
	return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}

function SetCookie (name, value) {
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
	((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
	((path == null) ? "" : ("; path=" + path)) +
	((domain == null) ? "" : ("; domain=" + domain)) +
	((secure == true) ? "; secure" : "");
}

function DeleteCookie (name) {
	var exp = new Date();
	exp.setTime (exp.getTime() - 1);
	var cval = GetCookie (name);
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}



/* ----------------------------------------------------------------------
DisplayCampusLinks
This function hides the campus links on the home page if the user's
window is set to a small enough size that they would need to scroll.
It keeps the campus links from interfering with our content.

This runs both onload and onresize.
*/

function DisplayCampusLinks() {

	// If the campus link layer cannot be found return.
	if(!document.getElementById("campusLinks")) {
		return;
	}

	// Figure out the height of the visible window.
	if(document.documentElement && document.documentElement.clientHeight) {
		windowHeight = document.documentElement.clientHeight; // IE 6
	} else if(window && window.innerHeight) {
		windowHeight = window.innerHeight; // Mozilla, Netcape
	} else {
		windowHeight = 0;
	}

	// Figure out the height of the content
	if(document.body && document.body.scrollHeight) {
		contentHeight = document.body.scrollHeight;
	} else {
		contentHeight = 0;
	}

	// If we figured both out, determine whether to show campus links.
	if(contentHeight > 0 && windowHeight > 0 && windowHeight >= contentHeight) {
		document.getElementById("campusLinks").style.visibility = "visible";
	} else {
		document.getElementById("campusLinks").style.visibility = "hidden";
	}
}


/* ----------------------------------------------------------------------
KeepSessionAlive
This function rotates an image on the page to keep the session alive.
Requires the following code in the page:
<img src="/library/admin/hourglass.php" width="13" height="22" id="ksa"/>
*/
function KeepSessionAlive() {
	if(document.getElementById("ksa")) {
		var now = new Date();
		//alert('/library/admin/hourglass.php?'+now.getTime());
		document.getElementById("ksa").src = '/library/admin/hourglass.php?'+now.getTime();
		//window.status = '/library/admin/hourglass.php?'+time();
		setTimeout("KeepSessionAlive()", 60000);
	}
}

/* ----------------------------------------------------------------------
ConfirmBackdate
This function prompt the ref-blogger to back- or fore- date outside
normal ref-desk hours.
Requires the following code in the page:
<form onsubmit="return ConfirmBackdate(this.entered_on)">
*/
function ConfirmBackdate(dateField) {
	var hour = dateField.value.substr(11,2);
	if(hour < 10) {
		dateField.select();
		return confirm("This question will be entered before ten o'clock.\n" +
			"Do you want to continue without post-dating?");
	}
	if(hour == 17) {
		dateField.select();
		return confirm("This question will be entered after five o'clock.\n" +
			"Do you want to continue without back-dating?");
	}
	if(hour == 18) {
		dateField.select();
		return confirm("This question will be entered before seven o'clock.\n" +
			"Do you want to continue without post-dating?");
	}
	if(hour >= 22) {
		dateField.select();
		return confirm("This question will be entered after ten o'clock.\n" +
			"Do you want to continue without back-dating?");
	}
	return true;
}

/* ----------------------------------------------------------------------
RollDateBack
Scrolls the time-stamp back or forward by the defined interval when
the user presses the "b" or "f" key
Requires the following code in the page:
<input name="FIELDNAME" onkeypress="return RollDateBack(event,this)"/>

Add a tag with this ID to show a 12 hour version:
<span id="FIELDNAME_12hour"></span>
*/
function RollDateBack(e,dateField) {

	// Set the interval to move by.
	var interval = 10;

	// Figure out which key was pressed
	var key = 0;
	if (window.event) { key = window.event.keyCode; }
	else if (e) { key = e.which; }

	// B/b for Back-dating
	// F/f or P/p for Post-dating
	if(key == 98 || key == 66 || key == 102 || key == 70 || key == 112 || key == 80) {

		// Make sure the date is properly formatted.
		var reg = /^(\d{4}-\d{2}-\d{2} )(\d{2}):(\d{2})(:\d{2})$/i;
		var aDate = reg.exec(dateField.value);
		if(aDate == null) { return false; }

		// If going back, make the interval negative.
		if(key == 98 || key == 66) { interval *= -1; }

		var hour = aDate[2] * 1;
		var minute = aDate[3] * 1;

		minute += interval;

		if(minute < 0) {
			minute += 60;
			hour -= 1;
		} else if(minute >= 60) {
			minute -= 60;
			hour += 1;
		}

		// If outside of one day, stop.
		if(hour < 0 || hour > 23) { return false; }

		// Add leading zeros.
		if(minute < 10) { minute = "0" + minute; }
		if(hour < 10) { hour = "0" + hour; }

		// Update the date field.
		dateField.value = aDate[1] + hour + ':' + minute + aDate[4];

		// Update the 12-hour format portion if available
		if(document.getElementById(dateField.id+"_12hour")) {
			document.getElementById(dateField.id+"_12hour").innerHTML =
				(hour > 12 ? hour - 12 : (hour < 1 ? '12' : hour * 1) ) + ':' +
				minute + ' ' + (hour >= 12 ? 'pm' : 'am');
		}

		return false;

	}

	return true;

}
