function initNav(){
	var nav = document.getElementById('nav');
	var navlis = nav.getElementsByTagName('li');

	for (var i=0; i<navlis.length; i++){
		if (navlis.item(i).getElementsByTagName('ul')[0]){
			addAnEvent(navlis.item(i),'keyup',showNav);
			addAnEvent(navlis.item(i),'mouseover',showNav);
			addAnEvent(navlis.item(i),'mouseout',hideNav);
			addAnEvent(navlis.item(i),'blur',hideNav);
			addAnEvent(navlis.item(i),'focus',hideNav);
		}
	}
}
function hideNav(){
	this.getElementsByTagName('ul')[0].className = "";
}
function showNav(){
    this.getElementsByTagName('ul')[0].className = "show";
}

function initButtons(){
	var inputs = document.getElementsByTagName("input");
	for (var i = 0; i<inputs.length; i++){
		if(inputs[i].type=="image"){
			addAnEvent(inputs.item(i),'mouseover',buttonHover);
			addAnEvent(inputs.item(i),'mouseout',buttonHoverout);
			inputs.item(i).style.borderWidth = "0px"
		}
	}
}
function buttonHover(){
	if (this.src.indexOf("1") == -1){
		var file = this.src.split(".gif");
		this.src = file[0] + "1.gif";
	}
}
function buttonHoverout(){
	var file = this.src.split("1.gif");
	this.src = file[0] + ".gif";
}

function initLinks(){
	var hostname = window.location.hostname;
	hostname = hostname.replace("www.","").toLowerCase();
	var a = document.getElementsByTagName("a");	
	this.check = function(obj){
		var href = obj.href.toLowerCase();
		return (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? true : false;				
	};
	this.set = function(obj){
		obj.target = "_blank";
		obj.className += " external";
		obj.title += "This link will open in a new window.";
	};
	this.checkpdf = function(obj){
		var href = obj.href.toLowerCase();
		return (href.indexOf("pdf")!=-1) ? true : false;				
	};
	this.setpdf = function(obj){
		obj.target = "_blank";
		if (obj.className!="large" && obj.className!="thumb") {
			obj.innerHTML += " <img src=\"/img/ic-pdf.gif\" />";
			obj.className += " pdf";
		}
		obj.title += "This PDF will open in a new window.";
	};
	for (var i=0;i<a.length;i++){
		if(check(a[i])) set(a[i]);
		if(checkpdf(a[i])) setpdf(a[i]);
		if (a[i].className.indexOf("photopop") != -1) addAnEvent(a.item(i),'click',photopop);
	};		
};

function photopop(){
    appWindow = window.open (this.href,"appWindow","width=355,height=500,toolbar=0,resizable=1,scrollbars=1");
    appWindow.focus ();
    return false;
}

function initSubnav(){
	var subnav = document.getElementById('subnav');
	var subnavas = subnav.getElementsByTagName('a');
	for (var a=0; a<subnavas.length; a++){
		var currenthref=String(subnavas[a].href);
		var currentloc=String(document.location);
		currentloc = currentloc.split("#");
		currentloc = currentloc[0];
		if (unescape(currenthref)==unescape(currentloc)){
			subnavas[a].className="current"
		}
	}
}

function initSubnavNA(){
	var subnav = document.getElementById('box-newsarchives');
	var subnavas = subnav.getElementsByTagName('a');
	for (var a=0; a<subnavas.length; a++){
		var currenthref=String(subnavas[a].href);
		var currentloc=String(document.location);
		if (unescape(currenthref)==unescape(currentloc)){
			subnavas[a].className="current"
		}
	}
}

function insertFootnotes() {
  if(!document.getElementsByTagName) return; //object detection
  var spans = document.getElementsByTagName('span');
  var noteIndex = 1;
  for(var i=0; i<spans.length; i++) {
    if(spans[i].className == 'footnote') { //are we dealing with a footnote?
      var note = spans[i];
      var id = 'note-' + noteIndex++; //ID of the footnote <span>
      var idAnchor = id + '-a'; //ID of the footnote <a> (to expand/collapse the note)
     
      var tmpLinkText; //get the text to be linked
      for(var j=0;j<note.childNodes.length; j++) {
        if(note.childNodes[j].nodeName == '#text') {
          var tmp = note.childNodes[j];
          if(tmp.substringData && tmp.replaceData) { //more testing to prevent errors in bad browsers
            while(true) { //remove trailing spaces
              if(tmp.substringData(tmp.length-1,1) == ' ') {
                tmp.replaceData(tmp.length-1,1,'');
              }
              else {
                break;
              }
            }
          }
          tmpLinkText = tmp.nodeValue;
          break;
        }
      }
     
      var tmpNoteText; //get the text of the footnote
      for(var j=0;j<note.childNodes.length;j++) {
        if(note.childNodes[j].nodeName == 'SMALL') {
          tmpNoteText = note.childNodes[j].innerHTML;
          break;
        }
      }
     
      var okToContinue = (tmpLinkText == '' || tmpNoteText == '') ? false : true; //make sure that we actually have the information we need
      if(okToContinue) {
        note.innerHTML = ''; //clear the span to be safe
        var link = '<a href="javascript:expand(\''+idAnchor+'\',\''+id+'\')" id="'+idAnchor+'" title="Click to expand/collapse this footnote" class="expand">'+tmpLinkText+'</a>';
        var noteText = '<span id="'+id+'" class="hidden"> <span class="expand">'+tmpNoteText+'</span></span>';
        note.innerHTML = link + noteText;
      }
    }
  }
}
function expand(aID,spanID) {
  if(!document.getElementById) return; //error prevention
  var anchor = document.getElementById(aID);
  var footnote = document.getElementById(spanID);
  footnote.className = (footnote.className == 'shown') ? 'hidden' : 'shown';
  anchor.className = (anchor.className == 'expand') ? 'collapse' : 'expand';
}

function initBranchingArticle(){
	var m = document.getElementById("main");
	var d = m.getElementsByTagName("div");
    var toc = document.getElementById("toc");
	toc.innerHTML += "&raquo; <a href=\""+document.location.pathname+"\">&nbsp;&nbsp;View Full Article</a>";
	var a = toc.getElementsByTagName("a");
	document.lastTarget = null;
    for (var i=0; i<d.length; i++) {
		if (location.hash!="") d[i].style.display="none";
        if (d[i].id && (d[i].id != "toc")) {						
            if (location.hash==("#" + d[i].id)) {
                d[i].style.display="block";
                document.lastTarget=d[i];
            } 
            for (var j=0; j<a.length; j++) {
                if (a[j].hash==("#" + d[i].id)) a[j].targetEl = d[i]; 
					   a[j].onclick = function() {

						for (var k=0; k<d.length; k++) {
							d[k].style.display="none";
						}

                    	if (document.lastTarget) document.lastTarget.style.display="none";
                    	if (this.targetEl) this.targetEl.style.display="block"; 
						document.lastTarget=this.targetEl;
                    	return true;
                }
            }
        }
    }    
}

function siteEmail(user){
	var hostname = "jnorman.com";
	document.write("<a href=" + "mail" + "to:" + user + "@" + hostname + ">" + user + "@" + hostname + "</a>")
}

var google_text_color = '#000000';

var google_link_colors = new Array('#ffff66','#a0ffff','#99ff99','#ff9999','#ff66ff');

function init_google(){
	var pattern = /google\./i;
	if (pattern.exec(document.referrer) != null){
		var url_parts = document.referrer.split('?');
		if (url_parts[1]){ 
			var url_args = url_parts[1].split('&');
			for(var i=0; i<url_args.length; i++){
				var keyval = url_args[i].split('=');
				if (keyval[0] == 'q'){
					go_google(decode_url(keyval[1]));
					return;
				}
			}
		}
	}
}

function decode_url(url){
	return unescape(url.replace(/\+/g,' '));
}

function go_google(terms){
	terms = terms.replace(/\"/g,"");
	var terms_split = terms.split(' ');
	var c = 0;
	for(var i=0; i<terms_split.length; i++){
		if (terms_split[i] != "and" && terms_split[i] != "a" && terms_split[i] != "an" && terms_split[i] != "or" && terms_split[i] != "if" && terms_split[i] != "of" && terms_split[i] != "the" && terms_split[i] != "but"){
			highlight_goolge(terms_split[i], document.getElementById("entries"),google_link_colors[c]);
			c = (c == google_link_colors.length-1)?0:c+1;
		}
	}
}

function highlight_goolge(term, container, color){
	var term_low = term.toLowerCase();

	for(var i=0; i<container.childNodes.length; i++){
		var node = container.childNodes[i];

		if (node.nodeType == 3){
			var data = node.data;
			var data_low = data.toLowerCase();
			if (data_low.indexOf(term_low) != -1){
				//term found!
				var new_node = document.createElement('SPAN');
				node.parentNode.replaceChild(new_node,node);
				var result;
				while((result = data_low.indexOf(term_low)) != -1){
					new_node.appendChild(document.createTextNode(data.substr(0,result)));
					new_node.appendChild(create_node_google(document.createTextNode(data.substr(result,term.length)),color));
					data = data.substr(result + term.length);
					data_low = data_low.substr(result + term.length);
				}
				new_node.appendChild(document.createTextNode(data));
			}
		}else{
			//recurse
			highlight_goolge(term, node, color);
		}
	}
}

function create_node_google(child, color){
	var node = document.createElement('SPAN');
	node.style.backgroundColor = color;
	node.style.color = google_text_color;
	node.appendChild(child);
	return node;
}

function addAnEvent(target, eventName, functionName){
	eval('target.on'+eventName+'=functionName');
}

function initPage(){
	if (document.getElementById){
		initNav();		
		initButtons();
		if (!document.getElementById('blog')) initLinks();
		if (document.getElementById('subnav')) initSubnav();
		if (document.getElementById('box-newsarchives')) initSubnavNA();
		insertFootnotes();
		if (!document.all && document.getElementById('toc')) initBranchingArticle();
		init_google();
	}
}

window.onload=initPage;