var Rules = {	
	'#table-of-contents li a:click, #content div a.same-toc:click, a.toc-anchor: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);
	},
	'#local-nav ul a, #local-nav ul span, #main-nav ul a, #main-nav ul span, #library-as-place ul a, #library-as-place 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) {
		window.open(element.href,'popup','resizable=yes,width=740,height=580');
		Event.stop(event);
	},
	/*'#three-column-menu,*/ '.three-block': function(element) {
		getHeights();
	},
	'#crossfade-container:loaded': function(element) {
		prepareDivs();
		startPage();
	},
	'.split-list': function(element) {
		splitList(element);
	}, 
	'#main-nav li.current' : function(element) {
		addCurrentHidden(element);
	},	
	'#content-wrapper:loaded': function(element) {
		createCitations(element);
	},
	'.randomized-container': function(element) {
		randomizeImage(element);
	},
	'#split-list-by-6': function(element) {
		splitBySix(element);
	}
}

function randomizeImage(element) {
	
	featured_items = element.getElementsByTagName('li');
	num_items = featured_items.length
	num = Math.floor(Math.random() * num_items);
	for (var i = 0; i < num_items; i++) {
		if (i != num) 
			featured_items[i].style.display = 'none';
		else
			featured_items[i].style.display = 'block';
	}
}

function getPreviousSiblingElement(element) {
	var node = element.previousSibling;
	while (node) {
		if (node.nodeType == 1) {
			return node;
		}
		node = node.previousSibling;
	}
	return null;
}


/* IMAGE ROTATION */

// The starting index in the above array.  It should be set to the 
// value of the div which doesn't have the CSS Display property 
// set to "none"
var i = 0;

// the number of milliseconds between swaps.  
// var wait = 4000;

var onlyOne = false;

/*
	This first function simply hides all the <div> elements that contain 
	events after the first one. When the page initially loads, we only 
	want the first event displaying.
*/
function prepareDivs() {
	
	var crossfade_container = document.getElementById('crossfade-container');
	var divs_to_rotate = crossfade_container.getElementsByTagName("div");
	
	if (divs_to_rotate.length > 1) {
		for (var k = 1; k < divs_to_rotate.length; k++) {
			divs_to_rotate[k].style.display = "none";
		}
	} else {
		onlyOne = true;
	}
}

/* 
	The function that performs the fade. The heavy lifting is done by the 
	scriptaculous javascript library functions Fade and Appear. 
*/
function swapFade(divs_to_rotate) {

	var crossfade_container = document.getElementById('crossfade-container');
	var divs_to_rotate = crossfade_container.getElementsByTagName("div");
	
	var divs_to_fade = new Array();
	for (var j = 0; j < divs_to_rotate.length; j++) {
		var current_div_id = divs_to_rotate[j].getAttribute("id");
		divs_to_fade.push(current_div_id);
	}

	if (divs_to_rotate.length > 1) {	
		Effect.Fade(divs_to_fade[i], { duration:1, from:1.0, to:0.0 });
		i++;
		if (i == divs_to_fade.length) i = 0;
		Effect.Appear(divs_to_fade[i], { duration:1, from:0.0, to:1.0 });
	}
}

// the onload event handler that starts the fading.
function startPage() {
	setInterval('swapFade()',wait);
}

function getPreviousSiblingElement(element) {
	var node = element.previousSibling;
	while (node) {
		if (node.nodeType == 1) {
			return node;
		}
		node = node.previousSibling;
	}
	return null;
}

function getHeights() {
	var left_height = $('left').getDimensions().height;
	var center_height = $('center').getDimensions().height;
	var right_height = $('right').getDimensions().height;
	
	var max_height;
	if (left_height > center_height) 
		if (left_height > right_height)
			max_height = left_height;
		else 
			max_height = right_height;
	else 
		if (center_height > right_height)
			max_height = center_height;
		else 
			max_height = right_height;
			
//	alert(max_height);
	$('left').setStyle({ height: max_height + 'px'});
	$('left').style.marginTop = 0;
	$('center').setStyle({ height: max_height + 'px' });
	$('center').style.marginTop = 0;
	$('right').setStyle({ height: max_height + 'px'});
	$('right').style.marginTop = 0;
}

function splitList(list) {

	var second_half = document.createElement("ul");
	second_half.setAttribute("id","second-half");
	
	var list_ul = list.getElementsByTagName("ul")[0];
	var committees = list_ul.getElementsByTagName("li");

	var second_half_start;
	if (committees.length % 2 == 1)
		second_half_start = committees.length / 2 + .5;
	else 
		second_half_start = committees.length / 2;

	// don't need to increment because as the 
	// node is removed, i becomes the next node
	for (var i = second_half_start; i < committees.length; ) 
		second_half.appendChild(committees[i]);
	
	list.appendChild(second_half);
}

function toggleTarget(element) {
	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") {
		Effect.BlindDown(target, {duration: 0.3});
	}
	else {
		Effect.BlindUp(target, {duration: 0.3});
	}
}

function fixTOC(url, tocElement) {
	var section = getBestTOCSection(url, tocElement);
	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 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 addCurrentHidden(element) {
	licurrent = $(element).firstChild;
	main_nav = $("main-nav");
	h1 = document.createElement("h1");
	h1.innerHTML = licurrent.innerHTML;
	main_nav.appendChild(h1);
	addClass(h1, "hidden");
}

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 splitBySix(split_six) {

	var second_list = document.createElement("ul");
	second_list.setAttribute("id","second");
	var third_list = document.createElement("ul");
	third_list.setAttribute("id","third");
	var forth_list = document.createElement("ul");
	forth_list.setAttribute("id","forth");
	var fifth_list = document.createElement("ul");
	fifth_list.setAttribute("id","fifth");
	var sixth_list = document.createElement("ul");
	sixth_list.setAttribute("id","sixth");
	
	var split_six = $('split-list-by-6');
	var list = split_six.getElementsByTagName("li");
	var num_items = list.length;
	var remainder = num_items % 6;
	var items_per_list = (num_items - remainder) / 6;
	if (num_items % 6 > 0)
		items_per_list = parseInt(num_items / 6) + 1
	else 
		items_per_list = num_items / 6;						
	
	var second_list_start = items_per_list + 1;
	var third_list_start = items_per_list * 2 + 1;
	var forth_list_start = items_per_list * 3 + 1;
	var fifth_list_start = items_per_list * 4 + 1;
	var sixth_list_start = items_per_list * 5 + 1;
	
	var append_list = second_list;
	var counter = second_list_start;
	for (var i = second_list_start - 1; i < list.length;) {
		
		if (counter == third_list_start ) {
			append_list = third_list;
		} else if (counter == forth_list_start ) {
			append_list = forth_list;
		} else if (counter == fifth_list_start ) {
			append_list = fifth_list;
		} else if (counter == sixth_list_start ) {
			append_list = sixth_list;
		} 
		append_list.appendChild(list[i]);
		counter++;
	}
	split_six.appendChild(second_list);
	split_six.appendChild(third_list);
	split_six.appendChild(forth_list);
	split_six.appendChild(fifth_list);
	split_six.appendChild(sixth_list);
}