/*javascript*/

/* CONTENTS 

I. Utilities
a) general
b) cookies

II. Appearence

III. Focus functions for the accessibility stuff

*/

/* I. UTILITIES */

/* a. general */

//preload an image
function loadImg(src){
//accepts src: the src attribute of the image to load
//does not return
var img = new Image();
img.src = src;
}

//get element by id
function id(id){
//accepts id
//returns element
return document.getElementById(id);
}

//get element by tagname
function tn(tn)
{
//accepts tagname
//returns array of elements
return document.getElementsByTagName(tn);
}

//make new element
function mTag(t, txt){
//accepts t the tag to be made
//and txt text of the tag optional
//returns a tag to be appended/used as required
var tag = document.createElement(t);
if (txt) { //any text
	 var tagTxt = document.createTextNode(txt);
	 tag.appendChild(tagTxt);
	 }
return tag;
}
/*
function mTag(tag, pTag){
  if(!pTag){
	  var pTag = document.createDocumentFragment();
	};
	var nTag = document.createElement(tag.typ);
	if(tag.txt){//text
	  var tTxt = document.createTextNode(tag.txt);
		nTag.appendChild(tTxt);
	}; 
	if(tag.attr){//attributes
	  for(var key in tag.attr){
		  if(key == 'xclass'){//classname
			  nTag.className = tag.attr[key];
			}//may need more IE specifics
			else{
		    nTag.setAttribute(key.substr(1), tag.attr[key]);
			};
		};
	};
	if(tag.handle){
		for(var key in tag.handle){
		  addHandler(nTag,tag.handle[key][0],tag.handle[key][1]);
		};
	};
	if(tag.childs){//has child nodes
	  var len=tag.childs.length;
	  for(var i=0; i<len ;i++){
		  mTag(tag.childs[i],nTag);
		};
	};	
	pTag.appendChild(nTag);
	//methods
	this.add = function(node){
	  node.appendChild(pTag);
	};
	this.insert = function(node){
	  node.parentNode.insertBefore(pTag,node);
	};
	this.after = function(node){
	  if(node.nextSibling){
		  node.nextSibling.parentNode.insertBefore(pTag,node.nextSibling);
		} 
		else{
		  node.parentNode.appendChild(pTag);
		};
	};
  return this;
};
*/
var EventCache = function(){
//by Mark Wuben
//http://novemberborn.net/javascript/event-cache
//don't copy from here go to site
  var listEvents = [];
  return {
    listEvents : listEvents,
    add : function(node, sEventName, fHandler){
    listEvents.push(arguments);
    },
    flush : function(){
		  var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
        item = listEvents[i];
        if(item[0].removeEventListener){
          item[0].removeEventListener(item[1], item[2], item[3]);
        };
        if(item[1].substring(0, 2) != "on"){
          item[1] = "on" + item[1];
        };
        if(item[0].detachEvent){
          item[0].detachEvent(item[1], item[2]);
        };
        item[0][item[1]] = null;
      };
			addHandler = null;
    }
  };
}();



var addHandler = function(el, typ, funct, capture){
  var i = 0;
  if (window.addEventListener){ //w3c DOM model
    return addHandler = function(el, typ, funct, capture){
      el.addEventListener(typ, funct, capture);	 
      };
  };
  if (window.attachEvent){ //IE DOM model
    return addHandler = function(el, typ, funct){ 
		  i++;
			var handle = 'fx' + typ + i;
		  try{
			  el.setAttribute(handle,'on');//won't work on first run
				}
			catch(e){//don't handle
			}
		  var fn = function(){
			  var trg = window.event.srcElement;
        if (trg){
					var tag = handle;
				  while (trg.getAttribute(tag)!='on'){
				    trg = trg.parentNode;
				    };
					};
			  funct.call(trg);
				};
      el.attachEvent('on' + typ, fn);
			EventCache.add(el, typ, fn);
    };
  };
}();



addHandler(window, 'unload', EventCache.flush);


//get mouse position
function getMouse(e){
//accepts the event
//returns a length 2 array x-position & y-position
if (e.pageX){//w3c DOM
	  		x = e.pageX;
				y = e.pageY;
				}
		else if (e.clientX){//IE model
				 x = e.clientX;
				 y = e.clientY;
				 }
return [x, y];
}

//get top and left of an element
function getOffsets(el) {
//accept the element to find the left/top of
var left = 0;
var top = 0;
while (el.offsetParent){//has a parent object 
			//this will continue until el.offsetParent is null ie the html tag
			left += el.offsetLeft;
			top += el.offsetTop;
			el = el.offsetParent;
			}
return [left, top];
}

/* b. cookie handlers */

//add cookie		 
function bakeCookie(name, value, age, path){
//creates a new cookie
//accepts name of cookie
//value: value to store
//age: max age in seconds may be set to 0 for a session cookie
//path: optional
var cookieString = name + "=" + encodeURIComponent(value);//get rid of illegal characters
if (age != 0) { //persistant cookie
	 cookieString += '; max-age=' + age;
	 }
if (path){ //path other than root
	 cookieString += '; path=' + path;
	 }
	 else{
	     cookieString += ';path=/';
			 }
	 
document.cookie = cookieString;
}


//read cookie
function readCookie(name){
//accepts name name of cookie to read
if (document.cookie == '') return false; //no cookie
var at = document.cookie.indexOf(name + '='); //where the cookie is at in the cookies
if (at != -1){ //not found
	 		 var start = at + name.length + 1; //start of value
	 		 if (document.cookie.indexOf(';', start) != -1){ //not the last cookie
	 		 		var end = document.cookie.indexOf(';', start); //end of value 
	 				return decodeURIComponent(document.cookie.substring(start, end));
	 				}
	 		 else{ //last cookie
	 		 		return decodeURIComponent(document.cookie.substring(start));
	 				}
						
	   }
	 
}

//delete cookie
function delCookie(name) {
//accepts name; name of cookie to be deleted
bakeCookie(name, '', -1);  //ie create a new cookie of same name with a max-age of -1
}

function hasCookies(){
//are cookies on?
bakeCookie('test', 'on', 0);
if (readCookie('test')!='on'){
    return false
		}
		else{
		    return true;
		    }
}



// II. APPEARANCE STUFF

function doFocus(){
//focus stuff for bloody IE
var links = document.getElementsByTagName('a');
if(!links) return;
for(var i=0; i < links.length; i++){
    if (links[i].className == ''){
        addHandler(links[i], 'focus', getFocus);
		    addHandler(links[i], 'blur', loseFocus);
				}
    }
}

function getFocus(){
this.className = 'focused';
}
		
function loseFocus(){
this.className = '';
}

function columnMatch(){
//resize content height to match that of the navigation
var bod = document.body;
var content = id('content');
var navigation = id('sidebar');
if (!navigation) return;//no nav
if (bod.clientWidth < 800){//going to be linearized
    content.style.height = '';
		navigation.style.height = '';
		return;
		}
var nav_high = navigation.offsetHeight;
var con_high = content.offsetHeight
if (nav_high > con_high){//navigation taller than content
    content.style.height = nav_high + 'px';//resize content
    }
}

function doChord(){
//linearize the layout to cope with lo-res hi text
var blnBig, blnSmall
var bod = document.body;
var head = id('crumb');
if (!head) return;
if (bod.clientWidth < 760){
    bod.className = 'small';
		}
		else if (bod.clientWidth < 850){
		  bod.className = 'narrow';
			}		
    else{
		  bod.className = null;
			}
if (head.clientHeight > 30) bod.className = 'small';//doesn't work for ie but that's ok
}


addHandler(window, 'load', doChord);
addHandler(window, 'resize', doChord);
addHandler(window, 'load', columnMatch);
addHandler(window, 'resize', columnMatch);
addHandler(window, 'load', doFocus);

//Google search form

function hideLabel(){
var lbl = this.previousSibling;//for the label
while (lbl.nodeType != 1){//not the label
lbl = lbl.previousSibling;
    }
lbl.className = 'hidden';
}

function showLabel(){
if (this.value) return;
var lbl = this.previousSibling;//for the label
while (lbl.nodeType != 1){//not the label
lbl = lbl.previousSibling;
    }
lbl.className = '';
}

function doGoogle(){
var lbl = id('google').getElementsByTagName('label')[0];
var fld = id('q');
if (!fld || !lbl) return;
lbl.style.position = 'absolute';
lbl.style.paddingTop = '0.2em';
lbl.style.paddingLeft = '0.2em';
fld.size = 25;
addHandler(fld, 'focus', hideLabel);
addHandler(fld, 'blur', showLabel);
//glow login
var user = id('loginid');
var pass = id('password');
addHandler(user, 'focus', hideLabel);
addHandler(pass, 'focus', hideLabel);
addHandler(user, 'blur', showLabel);
addHandler(pass, 'blur', showLabel);
}



addHandler(window, 'load', doGoogle);


//Table of contents

function getTOC(){
//create and append a table of contents
var arrHeads = id('content').getElementsByTagName('h2');
if (arrHeads.length < 2) return; //not worth it
var frag = document.createDocumentFragment();
frag.appendChild(mTag('h3','Page Contents'));
var list = mTag('ul');
list.className = 'page_cont';
for (var i=0; i < arrHeads.length;i++){   
    arrHeads[i].id = 'head' + i;
    var listItem = mTag('li');
		var txt = arrHeads[i].textContent || arrHeads[i].lastChild.nodeValue
		var anch = mTag('a', txt);
		anch.href = '#head' + i;
		anch.onclick = lightHead;
		listItem.appendChild(anch);
		list.appendChild(listItem);
		}
frag.appendChild(list);
id('sidebar').insertBefore(frag,id('sidebar').lastChild);
/*mTag({typ:'h3',txt:'Page contents'}).add(id('sidebar'))
var obj = {};
obj.typ = 'ul';
obj.childs = [];
for (var i=0; i < arrHeads.length; i++){
  arrHeads[i].id = 'head' + i; 
	obj.childs.push(
	  {
	  typ:'li',
		childs:[
		  {typ:'a',
			 txt:arrHeads[i].textContent||arrHeads[i].lastChild.nodeValue,
			 attr:{xhref:'#head' + i},
			 handle:{first:['click',lightHead]}}
		  ]
	  }
	);
};
mTag(obj).add(id('sidebar'));*/
}

function lightHead(){
//highlight heading
var start = this.href.indexOf('#') + 1;
var toLight = id(this.href.substr(start));
toLight.className = 'light';
window.setTimeout("clearOld()", 1000);
}

function clearOld(){
var old = id(location.hash.substr(1));//get old
if (old){
    old.className = '';
		}
}

addHandler(window, 'load', getTOC);


