// IE Mac compatibility code
if(typeof Array.prototype.push=='undefined')
  Array.prototype.push=function(){
    var i=0;
    b=this.length,a=arguments;
    for(i;i<a.length;i++)this[b+i]=a[i];
    return this.length
  };

// Utility Functions
window.loadTasks = new Array();
window.unloadTasks = new Array();
if(typeof EventManager != 'undefined') {
	EventManager.Add(window, 'load', driverInit, false);
	EventManager.Add(window, 'unload', driverFinish, false);
}
else {
	window.onload = driverInit;
	window.onunload = driverFinish;
}

//////////////////////////////////////////////
var Behaviour = {
	list : new Array,
	
	register : function(sheet){
		Behaviour.list.push(sheet);
	},
	
	start : function(){
		Behaviour.addLoadEvent(function(){
			Behaviour.apply();
		});
	},
	
	apply : function(){
		for (h=0;sheet=Behaviour.list[h];h++){
			for (selector in sheet){
				list = document.getElementsBySelector(selector);
				
				if (!list){
					continue;
				}

				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	},
	
	addLoadEvent : function(func){
		var oldonload = window.onload;
		
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
}

Behaviour.start();

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    
    if (!currentContext[0]){
    	return;
    }
    
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

//////////////////////////////////



// Standard dynamic nav stuff
Behaviour.register({
	'LI.topLevelNavItem' : function(e) {
		EventManager.Add(e, 'mouseover', function(){menuMouseOver(e);}, false);
		EventManager.Add(e, 'mouseout', function(){menuMouseOut(e);}, false);
	},
	'UL.subNav LI.hasChildren' : function(e) {
		EventManager.Add(e, 'mouseover', function(){menuMouseOver(e);}, false);
		EventManager.Add(e, 'mouseout', function(){menuMouseOut(e);}, false);
	}
});
	
function registerLoadTask(fn) {
	window.loadTasks.push(fn);
}

function registerUnloadTask(fn) {
	window.unloadTasks.push(fn);
}

function driverInit() {
	for(var i in window.loadTasks) {
		switch(typeof window.loadTasks[i]) {
		case 'string':
			eval(window.loadTasks[i]);
			break;
		case 'function':
			window.loadTasks[i]();
		}
	}
}

function driverFinish() {
	for(var i in window.unloadTasks) {
		switch(typeof window.unloadTasks[i]) {
		case 'string':
			eval(window.unloadTasks[i]);
			break;
		case 'function':
			window.unloadTasks[i]();
		}
	}
}

// Pop-ups
registerLoadTask(function() {addLinkHandlers("A");});
registerLoadTask(function() {addLinkHandlers("AREA");});

function addLinkHandlers(tagname) {
	var links = document.getElementsByTagName(tagname);
	for(i=0; i < links.length; i++) {
		var link = links[i];
		if(rel=link.getAttribute('rel')) {
			link.onclick = function(){return handleLinkRel(this);};
		}
	}
}

function handleLinkRel(link) {

	var relbits = link.getAttribute('rel').split('|');
	var href;
	if(typeof link.getAttribute == 'undefined')
		href = link.href;
	else
		//* This one is correct in both IE6 and Firefox
		href = link.getAttribute('href', 2);

	switch(relbits[0]) {
		case 'popup':
  			switch(relbits.length) {
  				case 1:
  					// No parameters
  					window.open(href);
  					break;
  				case 2:
  					// One parameter. Use it for window properties
  					window.open(href, null, relbits[1]);
  					break;
  				case 3:
  				default:
  					// Two (or more) parameters. Use 'em both
  					window.open(href, relbits[1], relbits[2]);
  					break;
  			}
			return false;
  			break;
  		default:
  			//Unknown link rel -- do nothing
			return true;
	}
}

function showurlin(url, dest, options) {
	switch(dest) {
	case 'popup':
		window.open(url, 'popup', options);
		break;
	case 'original':
    	if (window.opener && window.opener.location)
			window.opener.location.href = url;
		else
//			return false;
		break;
	default:
	}
//	return true;
}

function showPrintableVersion() {
	var url = 'printer.asp';
	url += window.location.search;
	window.open(url, 'popup', '');
}

// Image swapping
function imgSwap(obj, newsrc) {
	if(typeof obj == 'string') {
		obj = document.getElementById(obj);
	}
	if(!obj) return;
	obj.oldsrc = obj.src;
	obj.src = newsrc;
	return true;
}

function imgRestore(obj) {
	if(typeof obj == 'string') {
		obj = document.getElementById(obj);
	}
	if(!obj) return;
	if(obj.oldsrc) obj.src = obj.oldsrc;
	return true;
}

// Dynamic menus
var menuShowDelay = 200;
var menuHideDelay = 500;
window.visibleMenus = new Array();

function menuMouseOver(node) {
	if(!node) {return;}
	node.className += ' over';
	var menu = findMenu(node);
	if(!menu) return;
	if(menu.showPending) {window.clearTimeout(menu.showPending); menu.showPending = false;}
	if(menu.hidePending) {window.clearTimeout(menu.hidePending); menu.hidePending = false;}
	if(menu.style.display == 'block') return;
	menu.showPending = setMenuShowTimeout(menu, menuShowDelay);
}

function menuMouseOut(node) {
	if(!node) {return;}
	node.className = node.className.replace(/(^|\s)over(\s|$)/g, '');
	var menu = findMenu(node);
	if(!menu) return;
	if(menu.showPending) {window.clearTimeout(menu.showPending); menu.hidePending = false;}
	if(menu.hidePending) {window.clearTimeout(menu.hidePending); menu.showPending = false;}
	if(menu.style.display == 'none') return;
	menu.hidePending = setMenuHideTimeout(menu, menuHideDelay);
}

function findMenu(node) {
	if(typeof node.getElementsByTagName != 'undefined') {
		var children = node.getElementsByTagName('DIV');
		if(children)
			return children[0];
		else
			return null;
	}
	else {
		var children = node.childNodes;
		for(var i=0; i < children.length; i++)
			if (children[i].nodeName == 'DIV')
				return children[i];
		return null;
	}
}

function setMenuShowTimeout(object, delay) {
    return setTimeout('showMenu("'+object.id+'")', delay);
}

function setMenuHideTimeout(object, delay) {
    return setTimeout('hideMenu("'+object.id+'")', delay);
}

function hideMenusNow() {
	var vis = window.visibleMenus;
	var newvis = new Array();
	var i = 0;
	for(i=0; i < vis.length; i++) {
		var menu = vis[i];
		if(menu.hidePending) {
			window.clearTimeout(menu.hidePending);
			menu.hidePending = false;
			menu.style.display = 'none';

			var menuUL = menu.getElementsByTagName('UL')[0];
			if (menuUL && typeof menuUL.oldLeft != 'undefined') menuUL.style.left = menuUL.oldLeft;
		}
		else {
			newvis.push(vis[i]);
		}
	}
	window.visibleMenus = newvis;
}

function hideMenu(id) {
	var menu = document.getElementById(id);
	if(!menu) return;
	var vis = window.visibleMenus;
	var newvis = new Array();
	menu.style.display = 'none';
	for(var i = 0; i < vis.length; i++) {
		if(vis[i] != menu) {
			newvis.push(vis[i]);
		}
	}
	window.visibleMenus = newvis;

	var menuUL = menu.getElementsByTagName('UL')[0];
	if (menuUL && typeof menuUL.oldLeft != 'undefined') menuUL.style.left = menuUL.oldLeft;
}

function showMenu(id) {
	var menu = document.getElementById(id);
	if(!menu) return;
	hideMenusNow();
	document.body.style.overflowX = 'hidden';
	menu.style.visibility = 'hidden';
	menu.style.display = 'block';
	window.visibleMenus.push(menu);

	var viewportWidth = document.getElementsByTagName('BODY')[0].offsetWidth;
	var menuUL = menu.getElementsByTagName('UL')[0];
	if(menuUL) {
		var menuWidth = menuUL.offsetWidth;
		var menuLeft = menuUL.offsetLeft;
		var tmp = menuUL;
		while(tmp = tmp.offsetParent) {
			menuLeft += tmp.offsetLeft;
		}
		if(menuLeft + menuWidth > viewportWidth) {
			// This menu would go off the right side of the viewport
			menuUL.oldLeft = menuUL.style.left;
			tmp = menu.parentNode;
			if(/\btopLevelNavItem\b/.test(tmp.className)) {
				// It's the first menu, align it to the right of the viewport
				//menuUL.style.left = (viewportWidth - menuLeft - menuWidth - 1) + 'px';

				// It's the first menu, align it at the right of parent
				menuUL.style.left = (tmp.offsetWidth - menuWidth + 1) + 'px';
			}
			else {
				// It's a sub-sub-menu, make it come out on the left
				menuUL.style.left = '-' + (menuWidth-5) + 'px';
			}
		}
	}
	menu.style.visibility = '';
	//document.body.style.overflowX = 'auto';
}

function isValidDate(d, m, y, acceptShortYear) {
	var day = parseInt(d, 10);
	var month = parseInt(m, 10);
	var year = parseInt(y, 10);
	if(isNaN(day) || isNaN(month) || isNaN(year)) return false;
	if(!acceptShortYear && ((''+y).length < 4)) return false;
	if(month < 1 || month > 12) return false;
	switch(month) {
	case 2:
		if (day > 29) return false;
		if (day == 29 && (year%4!=0 || (year%100==0 && year%400!=0))) return false;
	case 4:
	case 6:
	case 9:
	case 11:
		if (day > 30) return false;
	default:
		if (day > 31) return false;
	}
	return true;
}

