var util = {

  W3CDOM : document.getElementById && document.getElementsByTagName && document.getElementsByName,
  divsToHide: [],
  pagetitle: null,
  lenHidden: null,
 
  //initialize the page, adding events to all of the hider links
  init : function() {
  	util.pageTitle();
  	util.setMenu();
	var divs = document.getElementsByTagName('div');
	var length = divs.length;
	var divsToHide = Array();
	var j=0;
	for (var i=0; i<length; i++) {
		if (divs[i].className == "hider") {
			//build array of only divs that get hidden
			util.divsToHide[j] = divs[i].getElementsByTagName('div')[0];
			j++;
			//add event to unhide them to the links
			var link = divs[i].getElementsByTagName('a')[0];
			//link.href = "#";
			//link.title = link.firstChild.nodeValue;
			util.addEvent(link, 'click', util.unhide);
		}
	}
	//read cookie and hide/unhide based on that
	util.lenHidden = util.divsToHide.length;
	 // reading and applying cookie values related to expanding/collapsing display, if the cookie exists
	    var displayStatuses = util.findCookie(util.pagetitle);
	    if (displayStatuses) {
	       var theStatuses = displayStatuses.split('|');
	       for (var i=0; i<util.lenHidden; i++) {
	           util.divsToHide[i].className = theStatuses[i];
	       }          
    	    }
    	    else {
    	    	for (var i=0; i<util.lenHidden; i++) {
	    	           util.divsToHide[i].className = "hidden";
	       }   
    	    }
	var links = document.getElementsByTagName('a');
	var linksLen = links.length;
	for (var j=0; j<linksLen; j++) {
		var linkText = links[j].href.toLowerCase();
		if ((! /projects.isr.umich.edu\/csdi|ccsg.isr.umich.edu|c:|file:/.test(linkText)) || /GIF|gif|png|pdf|bmp|jpg|pretestingtable1/.test(linkText)) {
			//add event to open link in new window
			util.addEvent(links[j], 'click', util.newWindow);
			//if it is an external link, add a hidden url for printing
			if (! /projects.isr.umich.edu\/csdi|ccsg.isr.umich.edu/.test(linkText)) {
				var theurl =  links[j].href.replace(/\s|<br>+/g,'');
				if (links[j].firstChild.nodeValue) {
					//if there is no link text because itis an image, skip it
					var thedisplay = links[j].firstChild.nodeValue.replace(/\s|<br>+/g,'');
				}
				if (theurl != thedisplay) {
					//the url doesn't match what we are displaying for the link, so change the class to external
					//this doesn't work for IE7
					links[j].className = 'external';
					
				}
			}
		}
	}
	if (util.pagetitle != "Introduction" && util.lenHidden >0) {
		util.addLink();
	}
  },
  
  //set the menu item for current page to class named current and make translation menu items appear, if necessary
  setMenu : function() {
   	var currPage = location.href;
 	currPage = currPage.replace(/#\w*/,'');
  	var allPages = document.getElementById('subnav').getElementsByTagName('li');
  	var numAllPages = allPages.length;
  	for (i=0; i<numAllPages; i++) {
  		if (allPages[i].getElementsByTagName('a')[0].href == currPage) {
  			allPages[i].className = 'current';
  		}
  	  	if ((/trans_/.test(currPage) || /translation/.test(currPage)) && /trans_/.test(allPages[i].getElementsByTagName('a')[0].href)) {
  		//make the trans links visible
  			allPages[i].style.display = "block";
  		}	
  		else if (/trans_/.test(allPages[i].getElementsByTagName('a')[0].href)) {
  		//hide them
  			allPages[i].style.display = "none";
   		}
  	}

  	//alert(currPage + ' ' + allPages[0].getElementsByTagName('a')[0].href);
  },
  
  //open a new window for external links
  newWindow : function(e) {
  	var theurl =  this.href.replace(/\s+|<br>/g,'');
  	winRef = window.open(theurl, "new");
  	util.stopDefault(e);
  },
  
  //change the page title based on the h2 tag on each page
  pageTitle : function() {
    	var page = document.getElementById('contentarea');
  	var header = page.getElementsByTagName('h2');
	util.pagetitle = header[0].firstChild.nodeValue;
	document.title += ' :: ' + util.pagetitle;
  },
  
  //unhide the proper divs when a link is clicked
  unhide : function(e) {
  	if (this.parentNode.getElementsByTagName('div')[0]) {
    		var divToUnHide = this.parentNode.getElementsByTagName('div')[0];
    	}
    	else if (this.parentNode.parentNode.getElementsByTagName('div')[0]) {
    		var divToUnHide = this.parentNode.parentNode.getElementsByTagName('div')[0];
    	}
  	if (divToUnHide.className == "hidden") {divToUnHide.className = ""}
  	else {divToUnHide.className = "hidden"}
  	//update cookie
  	// looping through the groups, concatenating their values, and setting the cookie for expand or collapse status
	    var len = util.divsToHide.length;
	    for (var i=0, theData=''; i<len; i++) {
	        theData += util.divsToHide[i].className;
	        if (i != util.totalSubgroups - 1) {
	           theData += '|';
	        }
    	    }
  	util.createCookie(util.pagetitle,theData);
  	util.stopDefault(e);
  },
  
  // utility function for stopping structural markup default behavior; disables link hrefs in this case
  stopDefault : function(e) {
     if (!e) {e = window.event;}
     if (!e.preventDefault) {
         e.preventDefault = function() { this.returnValue = false; }
     }
     e.preventDefault();
     return false;
  },

  // utility function for adding events
  addEvent : function(obj, type, func) {
  if (!obj) {alert(func);}
  if (obj.addEventListener) {obj.addEventListener(type, func, false);}
  else if (obj.attachEvent) {
      obj["e" + type + func] = func;
      obj[type + func] = function() {obj["e" + type + func] (window.event);}
      obj.attachEvent("on" + type, obj[type + func]);
    }
    else {obj["on" + type] = func;}
  },
  
    // utility function for setting cookies
    createCookie : function(name,value) {
      var expiration = new Date();
      var duration = expiration.getTime() + (30 * 24 * 60 * 60 * 1000);
      expiration.setTime(duration);    
      var data = name + "=" + escape(value) + "; expires=" + expiration.toGMTString();
      document.cookie = data;
    },  
  
    // utility functions for retrieving cookie values
    findCookie : function(name) {
      var query = name + "=";
      var queryLength = query.length;
      var cookieLength = document.cookie.length;
      var i=0;
      while (i < cookieLength) {
        var startValue = i + queryLength;
        if (document.cookie.substring(i,startValue) == query) {
           return this.findValue(startValue);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) {break;}
      }
      return null;
    },
  
  findValue : function(startValue) {
      var endValue = document.cookie.indexOf(";", startValue);
      if (endValue == -1) {
         endValue = document.cookie.length;
      }
      return unescape(document.cookie.substring(startValue,endValue));
  },
  
  unhideAll : function(e) {
  	var linkText = this.firstChild.nodeValue;
  	if (/Unhide/.test(linkText)) {
  		for (var i=0; i<util.lenHidden; i++) {
		   util.divsToHide[i].className = "";
	        } 
  	}
  	else {
  		for (var i=0; i<util.lenHidden; i++) {
		   util.divsToHide[i].className = "hidden";
	        } 
  	}
  	//update cookie
	  // looping through the groups, concatenating their values, and setting the cookie for expand or collapse status
	    var len = util.divsToHide.length;
	    for (var i=0, theData=''; i<len; i++) {
		theData += util.divsToHide[i].className;
		if (i != util.totalSubgroups - 1) {
		   theData += '|';
		}
	    }
  	util.createCookie(util.pagetitle,theData);
  	util.stopDefault(e);
  },
  
  //add links to page in various locations
  addLink : function() {
   	if (document.getElementById('mainlist')) {
  		var list = document.getElementById('mainlist');
  	}
  	else {
  		var list = document.getElementsByTagName('ol')[0];
  	}
  	if (list && list.className != "plain") {
		div = util.createDiv();
		div2 = util.createDiv();
		list.parentNode.insertBefore(div,list);
		list.parentNode.insertBefore(div2,list.nextSibling);
  	}
  	if (document.getElementById('secondlist')) {
  		div = util.createDiv();
		div2 = util.createDiv();
		document.getElementById('secondlist').parentNode.insertBefore(div,document.getElementById('secondlist'));
  	}
  },
  
  //create the div to hold the links, then add the links and give them events
  //the links let you toggle hide all or unhide all for easier browsing
  createDiv : function() {
  	var hidelink = document.createElement('a');
    	var unhidelink = document.createElement('a');
    	hidelink.appendChild(document.createTextNode('Hide All Subsections'));
    	hidelink.href='';
    	hidelink.title = 'Hide all subsections in this chapter';
    	unhidelink.appendChild(document.createTextNode('Unhide All Subsections'));
  	unhidelink.href='';
  	unhidelink.title = 'Display all subsections in this chapter';
  	var div = document.createElement('div');
	div.className = 'hider';
	div.appendChild(hidelink);
	div.appendChild(document.createTextNode(' | '));
	div.appendChild(unhidelink);
	util.addEvent(hidelink, 'click', util.unhideAll);
	util.addEvent(unhidelink, 'click', util.unhideAll);
	return div;
  }

}
// object detection and initializing functionality
if (util.W3CDOM) {
	util.addEvent(window, 'load', util.init);
}
