var Rules = {
  '#table-of-contents li a:click, a.same-toc:click': function(element, event) {
		fixTOC(element.href, "table-of-contents");
		Event.stop(event);
	},
	'#table-of-contents:loaded': function(element) {
		fixTOC(window.location.href, "table-of-contents");
		// Keep from jumping to a stupid place on the page; 10msec is gonna be before the page is even done rendering...
		setTimeout("window.scroll(0, 0)", 10);
	},
	'#tabbed-search:loaded': function(element) {
		fixLWSTab(window.location.href);
	},
	'.jump-to-top': function(element) {
		Element.hide(element);
	},
	'#home #main-banner': function(element) {	
		if (!$('wrapper').className.match("with-feature") && !$(element).hasClassName("showcase")) {
			//randomize_image(element, '/images/home-banner-', 5, '.png');
			randomize_image(element, '/images/RedBanner', 4, 'Flat.jpg');
		}
	},
	'#local-nav ul a, #local-nav ul span': function(element) {
		// Remove the border from the first local nav element
		var item = element.parentNode;
		var sib = getPreviousSiblingElement(item);
		if (!sib) {
			element.style.border = "none";
		}
	},
	'a.popup-without-chrome:click': function(element, event) {
		if (element.nodeName == "IMG")
			element = element.parentNode
		window.open(element.href,'popup','resizable=yes,width=740,height=580');
		Event.stop(event);
	},
	'.initial-off, .toggled-off, #definitions dt, #definitions dd': function(element) {
		// addClass(element,"hidden");
		element.style.display = "none";
	},
	'.switch': function(element) {
		element.style.display = "inline";
	},
	'.switch:click': function(element, event) {
		var switchClasses = new Array();
		element.classNames().each(function(className) {
			if (className != 'switch') { switchClasses.push(className); }
		});
		var switchables = document.getElementsByClassName('switchable');
		switchClasses.each(function(c) {
			switchables.each(function(e) {
				if (e.hasClassName(c)) {
					// switch it on!
					e.style.display = "";
				}
			});
		});
		element.style.display = "none";
		Event.stop(event);
	},
	'.toggler': function(element) {
		elt = $(element);
		elt_parent = elt.up();
		if (elt_parent.nodeName == 'LI') {
			elt_parent.style.listStyleType = "none";
		}
		elt.style.paddingLeft = "14px";
		elt.style.background = "url(http://library.wisc.edu/images/plus.gif) left no-repeat";
	},
	'.toggler:click': function(element, event) {
		toggleTarget(element);
		Event.stop(event);
	},	
	'#content-wrapper:loaded': function(element) {
		createCitations(element);
	},
	'.defined-term:click': function(element, event) {
		popupDefinition(element,event);
		Event.stop(event);
	},
	'html:loaded': function(element) {
		if ($('intro') || $('top-ten')) {
			createDarkOverlay(element, $('home'));
		}
	},
	'#top-databases a#intro:click': function(element, event) {
		if (typeof IE6=="undefined") {
			getIntroList(event);
			Event.stop(event);
		}
	},
	'#top-databases a#top-ten:click': function(element, event) {
		if (typeof IE6=="undefined") {
			getTopTenList(event);
			Event.stop(event);
		}
	},
	'#ask-chat-button': function(element) {
		get_ask_button(element);
	},
	'#search-tabs': function(element) {
		create_tab_onclicks(element);
	},
	'#equipment-checkout-button': function(element) {
		random_number = Math.floor(Math.random()*4) + 1;
		if (random_number > 1) {
			$(element).setAttribute('src', '/images/equipment-button-' + random_number + '.png');
		}
	},
	'#my-accounts:loaded': function(element) {
		element.style.zIndex = 300;
		$('my-accounts-list').style.zIndex = 200;
		delayHoverEffect(element);
	},
	'#my-accounts-list a:click': function(element, event) {
	  recordLink(element, 'My Accounts', element.href, element.innerHTML);
	  Event.stop(event);
	},
        '#giving-showcase a:click': function(element, event) {
          glink = element.parentNode;   
          recordGiving(glink, 'Giving Showcase', glink, 'Giving Showcase');           
          Event.stop(event);
        }
}
 
function recordGiving(glink, gcategory, gaction, glabel) {
  try {
    
    //gaction = gaction.replace(/.*library.wisc.edu/i, "");
    _gaq.push(['_trackEvent', gcategory, gaction, glabel]);
    setTimeout('document.location = "' + glink + '"', 100);    
  }catch(err){}
  
}

function randomize_ask_photo(ele) {
  photo_count = 16;
	rnd_photo = (Math.floor(Math.random()*photo_count)) + 1;
	$(ele).setAttribute('src', '/images/ask-photos/photo-' + rnd_photo + '.png');
}

function delayHoverEffect(ele) {
	ele = $(ele);
	ele.removeClassName('no-js');
	ele.hoverIntent(
		function() {
			ele.toggleClassName('hover');
		},
		function() {
			ele.toggleClassName('hover');
		}
	);
}

function create_tab_onclicks(search) {
	search_tabs = $(search);
	search = $(search).up();
	the_links = search_tabs.select('a');
	the_links.each (function (elt) {
		elt.setAttribute('href', '#' + elt.getAttribute('href', 2).gsub(/.*index-(.*).html/, "#{1}"));
		//alert(elt.getAttribute('href', 2));
		elt.onclick = function() {
			if (!this.up().hasClassName('current')) {
				search_tabs.select('li.current')[0].removeClassName('current');
				search.select('div.current')[0].hide(); 
				search.select('div.current')[0].removeClassName('current');
				this.up().addClassName('current');
				tab_div = this.getAttribute('href', 2);
				section = tab_div;
				window.location.hash = section;
				tab_div = tab_div + '-tab';
				tab_div = tab_div.substring(1, tab_div.length)
				tab_div = $(tab_div);
				tab_div.addClassName('current');
				tab_div.show();
				return false;
			}				
		}
	}); // End div_list.each
}

function fixLWSTab(url) {
	selected_tab = url.match(/#(.*)/);
	if (selected_tab) {
		selected_tab = selected_tab[1];
		tabbed_search = $("tabbed-search");
		tabbed_search.select('div.current')[0].hide();
		tabbed_search.select('div.current')[0].removeClassName('current');
		tabbed_search.select('li.current')[0].removeClassName('current');
		$(selected_tab + "-tab").addClassName('current');
		$(selected_tab + "-tab").show();
		$(selected_tab + "-selector").up().addClassName('current');
	} else {
		window.location.hash = "books";
	}
}

function  get_ask_button(ask_div) {	
	new Ajax.Request('http://www.library.wisc.edu/get-chat-js', {
		method: 'get',
		evalJS: false,
		onSuccess: function(transport) {
			window.eval(transport.responseText);
			if (jabber_resources[0].long_show == 'available') {				
				update_div = new Element('a', {'href': '#' });
				update_div.onclick = function() {
					window.open('http://libraryhelp.library.wisc.edu/chat/askuwlibrary@chat.libraryhelp.library.wisc.edu?skin=10121&amp;theme=jsf-text&amp;title=Ask%20a%20Librarian&amp;identity=librarian','chat', 'resizable=1,width=350,height=350'); 
					return false;
				}
				online_img = new Element('img', {'src': 'http://library.wisc.edu/images/chat-now.png', 'alt': 'Click here to chat now.'});
				update_div.appendChild(online_img);
			} else {				
				update_div = new Element('img', {'src': 'http://library.wisc.edu/images/chat-now-offline.png', 'alt': 'Chat is offline.'});
			}
			$(ask_div).update(update_div);
		}
	});
}

function getPageSize() {
	var xScroll, yScroll;
		
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
		
	var windowWidth, windowHeight;
		
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}

	return [pageWidth,pageHeight];
}

function createDarkOverlay(element, body_home) {
	dark_overlay = document.createElement('div');
	dark_overlay.setAttribute('id', "dark-overlay");
	dark_overlay.onclick = function() {
		removeCommAList();
		this.hide();
	}
	body_home.appendChild(dark_overlay);
	$('dark-overlay').setStyle({
		width: '100%',
		left: '0',
		top: '0',
		position: 'absolute',
		height: getPageSize()[1] + "px",
		background: "transparent url(/images/overlay-dark.png) repeat scroll 0 0",
		display: "none",
		zIndex: 100
	});
}

function getTopTenList(event) {
	$('dark-overlay').style.height = getPageSize()[1] + "px";
	$('dark-overlay').show();
	if ($('top-databases-overlay'))
		removeCommAList();
	var mouse_click_y = getMousePosY(event);
	var mouse_click_x = getMousePosX(event);
	var url = '/top-ten-list.html';
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
		
			var top_databases_container = document.createElement("div");
			top_databases_container = $(top_databases_container);
			top_databases_container.addClassName("top-ten-overlay");
			top_databases_container.setAttribute("id","top-databases-overlay");
			top_databases_container.innerHTML = transport.responseText;
			$('home').appendChild(top_databases_container);
			
			var x_button = document.createElement("a");
			x_button.setAttribute("id","close-top-databases-box");
			x_button.setAttribute("href","#");
			x_button.onclick = function() {
				removeCommAList();
				return false;
			}
			var x_text = document.createTextNode("X");
			x_button.appendChild(x_text);
			top_databases_container.insertBefore(x_button,$('top-databases-heading'));
			top_databases_container = $(top_databases_container);
			var height = top_databases_container.getHeight();
			var y_pos = mouse_click_y - height;
			var x_pos = mouse_click_x - 40;
			
			top_databases_container.setStyle({
				top: y_pos + "px",
				left: x_pos + 'px',
				display: 'block'
			});
		}
	});
}

function getIntroList(event) {
	$('dark-overlay').style.height = getPageSize()[1] + "px";
	$('dark-overlay').show();
	if ($('top-databases-overlay'))
		removeCommAList();
	var mouse_click_y = getMousePosY(event);
	var mouse_click_x = getMousePosX(event);
	var url = '/intro-list.html';
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
		
			var top_databases_container = document.createElement("div");
			top_databases_container.setAttribute("id","top-databases-overlay");
			top_databases_container.innerHTML = transport.responseText;
			$('home').appendChild(top_databases_container);
			
			var x_button = document.createElement("a");
			x_button.setAttribute("id","close-top-databases-box");
			x_button.setAttribute("href","#");
			x_button.onclick = function() {
				removeCommAList();
				return false;
			}
			var x_text = document.createTextNode("X");
			x_button.appendChild(x_text);
			top_databases_container.insertBefore(x_button,$('top-databases-heading'));
			top_databases_container = $(top_databases_container);
			var height = top_databases_container.getHeight();
			var y_pos = mouse_click_y - height;
			var x_pos = mouse_click_x - 40;
			
			top_databases_container.setStyle({
				top: y_pos + "px",
				left: (Element.cumulativeOffset($('search-tools'))[0] - 6) + 'px',
				display: 'block'
			});
		}
	});
}

function removeCommAList() {
	$('home').removeChild($('top-databases-overlay'));
	$('dark-overlay').hide();
}

function toggleTarget(element) {
	removeCurrentPopupDefinition();
	var elt = $(element);
	if (!elt.href) { return false; }
	var target = $(getTargetIdFromAddress(elt.href));
	if (!target) {return false;}
	if (target.hasClassName("toggled-off")) {
		target.removeClassName("toggled-off");
	}
	if (target.style.display == "none") {
		window.location.hash = target.id;
		elt.style.background = "url(http://library.wisc.edu/images/minus.gif) left no-repeat";
		Effect.BlindDown(target, {duration: 0.3});
	}
	else {
		elt.style.background = "url(http://library.wisc.edu/images/plus.gif) left no-repeat";
		Effect.BlindUp(target, {duration: 0.3});
	}
}

function getTargetIdFromAddress(address) {
	// Given a string like "http://www.foo.com/bar/corge.html" reutrn "corge"
	
	var slashIndex = address.lastIndexOf('/');
	if (slashIndex == -1) { slashIndex = 0; }
	if (slashIndex != 0) { slashIndex += 1; }
	var dotIndex = address.lastIndexOf('.');
	if (dotIndex == -1) { dotIndex = address.length - 1; }
	return address.substring(slashIndex, dotIndex);
}

// TODO: Move this stuff out of this file

function randomize_image(element, prefix, limit, postfix) {
	num = Math.floor(Math.random()*limit + 1);
	if (element.src) {
		element.src = prefix+num+postfix;
	}
}

function showOnly(container, id) {
	container = $(container);
	var div_rule = "#"+container.id+" div";
	var div_list = $$(div_rule);
	div_list.each (function (elt) {
		if (elt.parentNode == container) {
			if (elt.id == id) {
				Element.removeClassName(elt, "hidden");
			}
			else {
				Element.addClassName(elt, "hidden");
			}
		}
	}); // End div_list.each
}

function setCurrent(tocElement, section) {
	tocElement = $(tocElement);
	var links = $$("#"+tocElement.id+" a");
	links.each( function(elt) {
		var regex = new RegExp("#"+section+"$");
		
		if (elt.href.search(regex) >= 0) {
			Element.addClassName(elt.parentNode, "current");
		}
		else {
			Element.removeClassName(elt.parentNode, "current");
		}
	});
}

function getTOCFromToggle(elt) {
	toc_item = '';
	elt_item = elt;
	while (elt_item.up().id != "content") {
		elt_item = elt_item.up();
	}
	if (elt_item.id)
		toc_item = elt_item.id;
	return toc_item;
}

function fixTOC(url, tocElement) {
	var section = getBestTOCSection(url, tocElement);
	sec = $(section);
	if (sec != null && sec.hasClassName("toggled-off")) {
		toggleTarget(sec.previous());
		section = getTOCFromToggle(sec);
	} else {
		window.location.hash = section; //section.replace('-', '_');
	}
	showOnly("content", section);
	setCurrent("table-of-contents", section);
}

function getBestTOCSection(url, tocElement) {
	var id = getLocalAnchor(url);
	if (id) { return id; }
	var toc = $(tocElement);
	var items = toc.getElementsByTagName("a");
	id = getLocalAnchor(items[0].href);
	return id;
}

function getLocalAnchor(url) {
	var match = url.match(/#(.*)/);
	if (match && match.length > 1) {
		return match[1];
	}
	return null;
}

function getPreviousSiblingElement(element) {
	var node = element.previousSibling;
	while (node) {
		if (node.nodeType == 1) {
			return node;
		}
		node = node.previousSibling;
	}
	return null;
}

function createCitations(container) {

	if (container.className.match("print-url-citations")) {
			
		var links = container.getElementsByTagName("a");
		var citation_holder = document.createElement("ol");
		var reference = 0;
	
		for ( var i=0; i < links.length; i++ ) {
	
			if ( (checkIfAnchor(links[i]) == false) && (checkIfMailto(links[i]) == false) ) {
	
				reference++;
				var superscript_ref = document.createElement("sup");
				var sup_ref_text = document.createTextNode(reference);
				superscript_ref.appendChild(sup_ref_text);
				links[i].appendChild(superscript_ref);
				
				var list_item = document.createElement("li");
				var link_to = links[i].getAttribute("href");
				
				// Safari sometimes defaults to shrink a page to the width of a long
				// URL, so I am chopping off the end of long ones.
				if (link_to.length > 75) {
					link_to = link_to.substring(0,75) + "...";
				}
				
				// This is used to relative catch links back to our web site.
				if (link_to.match(/^\//)) {
					link_to = "http://www.library.wisc.edu" + link_to
				}
				
				var url = document.createTextNode(link_to);
				list_item.appendChild(url);
				citation_holder.appendChild(list_item);
			}	
		}	

		var citations = document.createElement("div");
		citations.setAttribute("id","citations");
		container.appendChild(citations);
		var heading = document.createElement("h3");
		var h_text = document.createTextNode("URL References");
		heading.appendChild(h_text);
		citations.appendChild(heading);
		citations.appendChild(citation_holder);
		addClass(citations,"hidden");
	} else {
		return false;
	}
}

function checkIfAnchor(check_link) {
	if (check_link.parentNode.parentNode.parentNode.getAttribute("id") == "table-of-contents") {
		return true;
	}
	if (check_link.className.match(/jump-to-top/)) {
		return true;
	}
	return false;
}

function checkIfMailto(link) {
	if (link.getAttribute("href").match(/^mailto/)) {
		return true;
	} else {
		return false;
	}
}

function addClass(element,value) {
  if (!element.className) {
    element.className = value;
  } else {
    newClassName = element.className;
    newClassName+= " ";
    newClassName+= value;
		element.className = newClassName;
  }
}

function removeCurrentPopupDefinition() {
	if (document.getElementById("popup-holder")) {
		var last_popup = document.getElementById("popup-holder");
		last_popup.parentNode.removeChild(last_popup);
	}
}

function popupDefinition(element,event) {
	// Remove any other popup definitions on the screen to remove clutter
	removeCurrentPopupDefinition();
	
	body_element = document.getElementsByTagName("body")[0];

	// Create a container to hold the popup definition background image 
	// and an inner container to hold the text. add the definition to it.
	var popup_holder = document.createElement("div");
	popup_holder.setAttribute("id","popup-holder");
	var def_element = document.getElementById(element.id + "-def");
	var def_holder = document.createElement("div");
	def_holder.innerHTML = def_element.innerHTML;
	def_holder.setAttribute("id","def_holder");
	popup_holder.appendChild(def_holder);

	// Attach ...
	body_element.insertBefore(popup_holder,body_element.firstChild);

//	body_element.style.margin = "0";
	// The user will need to close the popup definition, 
	// create a clickable 'X' to close the definition and append 
	// it to the definition.
	var close_link = document.createElement("a");
	var close_text = document.createTextNode("X");
	close_link.setAttribute("href","#");
	close_link.onclick = function() {
		closeDefinition(popup_holder,close_link);
		return false;
	}
	close_link.appendChild(close_text);
	close_link.style.color = "#fff";
	close_link.style.textDecoration = "none";
	close_link.style.display = "block";
	close_link.style.fontSize = "11px";
	close_link.style.height = "10px";
	close_link.style.width = "10px";
	close_link.style.position = "absolute";
	close_link.style.zIndex = "19";
	popup_holder.appendChild(close_link);
	
	def_holder.style.borderBottom = "1px solid #aaa";
	def_holder.style.fontSize = "1.3em";
	def_holder.style.padding = "1em .5em 2em";
	popup_holder.style.display = "block";
	popup_holder.style.position = "absolute";
	popup_holder.style.width = "200px";
	popup_holder.style.backgroundRepeat = "no-repeat";
	popup_holder.style.zIndex = "10";
	mouse_click_x = getMousePosX(event);
	mouse_click_y = getMousePosY(event);
	popup_holder.style.top = mouse_click_y - 70 + "px";
	if (document.body.clientWidth / 2 > mouse_click_x) {
		popup_holder.style.left = mouse_click_x + "px";
		popup_holder.style.backgroundImage = "url(/images/quick-definition.gif)";
		popup_holder.style.padding = "20px 0 0 50px";
		close_link.style.top = "3px";
		close_link.style.right = "3px";
	}	else {
		popup_holder.style.left = mouse_click_x - 280 + "px";
		popup_holder.style.backgroundImage = "url(/images/quick-definition-point-right.gif)";
		popup_holder.style.padding = "20px 50px 0 0";
		close_link.style.top = "3px";
		close_link.style.right = "53px";
	}
}

function getMousePosX(e) {
	var posx = 0;

	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
	}
	return posx;
}

function getMousePosY(e) {
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageY) 	{
		posy = e.pageY;
	}
	else if (e.clientY) 	{
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	return posy;
}

function closeDefinition(container,close_link) {
	close_link.parentNode.removeChild(close_link);
	container.parentNode.removeChild(container);
}

