// JavaScript Document

// THIS FUNCTION SHOULD EVENTUALL BE PLACED/INCLUDED IN A SEPARATE JAVSCRIPT FILE
function extendEmptyPanel() {
   var newHeight = (findCoord(document.getElementById('footer'))[1] - findCoord(document.getElementById('empty_panel'))[1] - 40);
    if (newHeight < 0) {
        newHeight = 0;
    }

    document.getElementById('empty_panel').style.height = newHeight + 'px';
}




// include CSS file
document.write('<link rel="stylesheet" type="text/css" href="styles/menu.css" />');


// IE 6.0 Flicker Bug fix
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}


// global to store the current page mainmenu item
var SLCTD_MM_ITEM;
// global to store the current page submenu caption
var SLCTD_SM_CAPTION;
// global to store the current page submenu bullet
var SLCTD_SM_BULLET;


/*
Params:
	itemId: The specified mainmenu item id.
Desc:
	Sets the specified mainmenu item to be selected permanently
*/
function mmMakeSelected(itemId) {
	// check if specified item exist
	if (SLCTD_MM_ITEM = document.getElementById(itemId)) {
		//set selected blurb to be the default 'home' blurb
		SLCTD_MM_ITEM.className = "item_down";
	}
}

/*
Params:
	itemId: The specified mainmenu item id.
	blurId: The specified blurb item id.
Desc:
	Switches the mainmenu item and shows the blurb item.
*/
function mmOver(itemId, blurbId) {
	// check if specified item exists
	if(menuItem = document.getElementById(itemId))
	{
		
		// activate specified item if it is not for the current page
		if (menuItem != SLCTD_MM_ITEM) {
			menuItem.className = "item_over";
		}
	
		var def_blrb = document.getElementById('default_blurb');
		
		// check if blurb exists, i.e. HOMEPAGE ONLY
		if (blurbItem = document.getElementById(blurbId)) {
			// show selected blurb
			blurbItem.style.visibility = "visible";
			// hide default blurb
			def_blrb.style.visibility = "hidden";
		}
	}
}

/*
Params:
	itemId: The specified mainmenu item id.
	blurId: The specified blurb item id.
Desc:
	Unswitches the mainmenu item and hides the blurb item.
*/
function mmOut(itemId, blurbId) {
	// check if specified item exists
	if(menuItem = document.getElementById(itemId))
	{
		// unactivate specified item if it is not for the current page
		if (menuItem != SLCTD_MM_ITEM) {
			menuItem.className = "item";
		}
	
		var def_blrb = document.getElementById('default_blurb');
		
		// check if blurb exists, i.e. HOMEPAGE ONLY
		if (blurbItem = document.getElementById(blurbId)) {
			// hide specified blurb
			blurbItem.style.visibility = "hidden";
			// hide default blurb
			def_blrb.style.visibility = "visible";
		}
	}
}

/*
Params:
	captionId: The specified submenu caption id.
	itemId: The specified mainmenu item id.
Desc:
	Sets the specified mainmenu item to be selected permanently.
*/
function smMakeSelected(captionId, bulletId) {
	// check if specified submenu caption exists
	if (SLCTD_SM_CAPTION = document.getElementById(captionId)) {	
		//set caption to be selected on pageload
		SLCTD_SM_CAPTION.className = "caption_down";
	}
	// check if specified submenu bullet exists
	if (SLCTD_SM_BULLET = document.getElementById(bulletId)) {	
		//set bullet to be selected on pageload
		SLCTD_SM_BULLET.className = "bullet_down";
	}
}


/*
Params:
	captionId: The specified submenu caption id.
	bulletId: The specified submenu bullet id.
Desc:
	Switches the color of the submenu bullet.
*/
function smOver(captionId, bulletId) {
	// check if submenu caption exists
	if(captionItem = document.getElementById(captionId)) {
		// change back color of caption if it is not for the current page
		if (captionItem != SLCTD_SM_CAPTION) {
			captionItem.className = "caption_over";
		}	
	}
	// check if submenu bullet exists
	if(bulletItem = document.getElementById(bulletId)) {
		// change color of bullet if it is not for the current page
		if (bulletItem != SLCTD_SM_BULLET) {
			bulletItem.className = "bullet_over";
		}		
	}
}

/*
Params:
	captionId: The specified submenu caption id.
	bulletId: The specified submenu bullet id.
Desc:
	Unswitches the color of the submenu bullet.
*/
function smOut(captionId, bulletId) {
	// check if submenu caption exists
	if(captionItem = document.getElementById(captionId)) {
		// change back color of caption if it is not for the current page
		if (captionItem != SLCTD_SM_CAPTION) {
			captionItem.className = "caption";
		}	
	}
	// check if submenu bullet exists
	if(bulletItem = document.getElementById(bulletId)) {
		// change back color of bullet if it is not for the current page
		if (bulletItem != SLCTD_SM_BULLET) {
			bulletItem.className = "bullet";
		}	
	}
}

/*
Params:
	mmItemPos: The item's postition in the mainmenu.
	mmNumItems: The number of items in the mainmenu.
	smItemPos: The item's postition in the submenu.
	smNumItems: The number of items in the submenu.
	smNumItems: The number of items in the submenu.
	expandDynamically: Boolean to decide if menu expand is dynamic or static.
Desc:
	Expands the submenu starting from its mainmenu position, with an
	'opacity' special effect for the square, an 'elevator' special
	effect for the vertical line, and both 'opacity' and 'text rollout'
	special effects for the submenu items.
*/
function smExpand(mmItemPos, mmNumItems, smItemPos, smNumItems, expandDynamically) {	
	var sqr = document.getElementById("square");
	var sqrCurrOpacity = 10;
	var sqrFullOpacity = 60;
	var sqrIncrOpacity = 5;
	var sqrOpacityIntervalTime = 50;
        
	var i = 0;
	var smAllItems = [];
	var smAllItems = document.getElementsBySelector("#sub_menu .item");
	
	var mmItemHeight = 31;
	var mmHeight = (mmNumItems - mmItemPos) * mmItemHeight;
	var smItemMarginHeight = 4;
	var smItemFinishingHeight = 13;
	var smItemCoord = [0, 0];
	var smItemCoordY = [];
	var smItemHeight = [];
	var smHeight = 0;
	for (var n = 0; n < smAllItems.length; n++) {
		smItemCoord = findCoord(smAllItems[n]);
		smItemCoordY[n] = smItemCoord[1];
		smItemHeight[n] = smAllItems[n].offsetHeight + smItemMarginHeight;

		// IE6 bug fix
		smAllItems[n].style.height = smAllItems[n].offsetHeight;
		smAllItems[n].style.visibility = "visible";

		// do for every submenu item, but the last one
		if (n < smAllItems.length - 1) {
			smHeight += smItemHeight[n];	
		}
		// do for the last submenu item
		else {
			smHeight += smItemFinishingHeight;
		}
	}
	var menuSpacerHeight = 37;
	
	var vl = document.getElementById("vert_line");
	var vlCurrHeight = 0;
	var vlFullHeight = mmHeight + menuSpacerHeight + smHeight;
	var vlIncrHeight = 0;
	var vlIincrHeightFactor = 20;
	var vlIncrHeightFactorCompensation = 0.08;
	var vlHeightIntervalTime = 20;
		
	var smItemsCaption = [];
	var smItemsCaptionText = [];
	var smItemsCaptionLength = [];
	var smItemsCaptionIndex = [];
	var smCaptionIntervalTime = 10;
	
	var smItemsCurrOpacity = 10;
	var smItemsFullOpacity = 100;
	var smItemsIncrOpacity = 7;
	var smItems = [];
	var smItemsOpacityCurr = [];
	var smItemsOpacityIncr = [];
	var smItemsOpacityFull = [];
	var smOpacityIntervalTime = 50;

        sqr.style.top = sqr.offsetTop + ((mmItemPos - 1) * mmItemHeight) + 'px';
        vl.style.top = vl.offsetTop + ((mmItemPos - 1) * mmItemHeight) + 'px';

	// check if the page is the first item of submenu
	if (expandDynamically == true) {
		// sqr opacity interval timer function
		var sqrOpacityInterval = setInterval(function() {
			// increasing the opacity of the sqr
			if ((sqrCurrOpacity + sqrIncrOpacity) < sqrFullOpacity) {
				sqr.style.opacity = (sqrCurrOpacity + sqrIncrOpacity) / 100;
				sqr.style.MozOpacity = (sqrCurrOpacity + sqrIncrOpacity) / 100;
				sqr.style.KhtmlOpacity = (sqrCurrOpacity + sqrIncrOpacity) / 100;
				sqr.style.filter = "alpha(opacity=" + (sqrCurrOpacity + sqrIncrOpacity) + ")";
				
				sqrCurrOpacity += sqrIncrOpacity;
			}
			// reaching the full opacity of the sqr
			else {
				sqr.style.opacity = sqrFullOpacity / 100;
				sqr.style.MozOpacity = sqrFullOpacity / 100;
				sqr.style.KhtmlOpacity = sqrFullOpacity / 100;
				sqr.style.filter = "alpha(opacity=" + sqrFullOpacity + ")";
				
				clearInterval(sqrOpacityInterval);
			}
		}, sqrOpacityIntervalTime);

		// vertical line interval timer function
		var vlHeightInterval = setInterval(function() {													
			// calculate next hieght increase increment
			vlIncrHeight = Math.ceil(((vlFullHeight - vlCurrHeight) + (vlFullHeight * vlIncrHeightFactorCompensation)) / vlIincrHeightFactor);
			
			// increasing the height of the vertical line
			if ((vlCurrHeight + vlIncrHeight) < vlFullHeight) {
				vlCurrHeight += vlIncrHeight;
				vl.style.height = vlCurrHeight + "px";
			}
			// reaching the full height of the vertical line
			else {
				vl.style.height = vlFullHeight + "px";
				clearInterval(vlHeightInterval);
			}
			
			// check if next submenu item needs to appear
			var vlCoord = findCoord(vl);
			var vlCoordY = vlCoord[1] + vlCurrHeight;

			if(vlCoordY >= smItemCoordY[i]) { // calculation for each next submenu items
			
                        	var smCaptionInterval = setInterval(function() {
					var smIC = smItemsCaption[smCaptionInterval%100];
					var smICT = smItemsCaptionText[smCaptionInterval%100];
					var smICL = smItemsCaptionLength[smCaptionInterval%100];
					var smICI = smItemsCaptionIndex[smCaptionInterval%100];
		
					// making the submenu item appear
					if (smICI <= smICL) {
						var newCaption = smICT.substring(0, smICI);
						// IE code
						if(document.all) {
							smIC.firstChild.nodeValue = newCaption;
						}
						// FireFox code
						else {
							smIC.firstChild.nodeValue = newCaption;									
						}
					}
					// finalizing the submenu items
					else {
						clearInterval(smCaptionInterval);								
					}
					
					smItemsCaptionIndex[smCaptionInterval%100]++;
				}, smCaptionIntervalTime);
				
				// submenu item opacity interval timer function
				var smOpacityInterval = setInterval(function() {
					smI = smItems[smOpacityInterval%100];
					smIOC = smItemsOpacityCurr[smOpacityInterval%100];
					smIOI = smItemsOpacityIncr[smOpacityInterval%100];
					smIOF = smItemsOpacityFull[smOpacityInterval%100];
							
					// increasing the opacity of the submenu item
					if ((smIOC + smIOI) < smIOF) {
						smI.style.opacity = (smIOC + smIOI) / 100;
						smI.style.MozOpacity = (smIOC + smIOI) / 100;
						smI.style.KhtmlOpacity = (smIOC + smIOI) / 100;
						smI.style.filter = "alpha(opacity=" + (smIOC + smIOI) + ")";
						
						smItemsOpacityCurr[smOpacityInterval%100] += smIOI;
					}
					// reaching the full opacity of the submenu item
					else {
						smI.style.opacity = smIOF / 100;
						smI.style.MozOpacity = smIOF / 100;
						smI.style.KhtmlOpacity = smIOF / 100;
						smI.style.filter = "alpha(opacity=" + smIOF + ")";
						
						clearInterval(smOpacityInterval);
					}
				}, smOpacityIntervalTime);
				
				// IE code, assign caption properties to its submenu item
				if(document.all) {
					smItemsCaption[smCaptionInterval%100] = smAllItems[i].lastChild;
					smItemsCaptionText[smCaptionInterval%100] = smAllItems[i].lastChild.innerText.trim();
					smItemsCaptionLength[smCaptionInterval%100] = smAllItems[i].lastChild.innerText.trim().length;
					smItemsCaptionIndex[smCaptionInterval%100] = 0;
					
					smItems[smOpacityInterval%100] = smAllItems[i];
					smItemsOpacityCurr[smOpacityInterval%100] = smItemsCurrOpacity;
					smItemsOpacityIncr[smOpacityInterval%100] = smItemsIncrOpacity;
					smItemsOpacityFull[smOpacityInterval%100] = smItemsFullOpacity;
					
					// clear caption text and begin the item to appear
					smAllItems[i].lastChild.firstChild.nodeValue = "";
				} 
				// FireFox code, assign caption properties to its submenu item
				else {
                    smItemsCaption[smCaptionInterval%100] = smAllItems[i].childNodes[5];
					smItemsCaptionText[smCaptionInterval%100] = smAllItems[i].childNodes[5].textContent.trim();
					smItemsCaptionLength[smCaptionInterval%100] = smAllItems[i].childNodes[5].textContent.trim().length;
					smItemsCaptionIndex[smCaptionInterval%100] = 0;
					
					smItems[smOpacityInterval%100] = smAllItems[i];
					smItemsOpacityCurr[smOpacityInterval%100] = smItemsCurrOpacity;
					smItemsOpacityIncr[smOpacityInterval%100] = smItemsIncrOpacity;
					smItemsOpacityFull[smOpacityInterval%100] = smItemsFullOpacity;
					
					// clear caption text and begin the item to appear
					smAllItems[i].childNodes[5].firstChild.nodeValue = "";
				}
				
				i++;
			}
		}, vlHeightIntervalTime);
	}
	// run this if the page is an item other than the first of the submenu
	else {
		// set sqr to full opacity
		sqr.style.opacity = sqrFullOpacity / 100;
		sqr.style.MozOpacity = sqrFullOpacity / 100;
		sqr.style.KhtmlOpacity = sqrFullOpacity / 100;
		sqr.style.filter = "alpha(opacity=" + sqrFullOpacity + ")";
		
		// set vertical line to full height
		vl.style.height = vlFullHeight + "px";
		
		// set all submenu items to be visible
		for(var j = 0; j < smNumItems; j++) {
			smAllItems[j].style.opacity = smItemsFullOpacity / 100;
			smAllItems[j].style.MozOpacity = smItemsFullOpacity / 100;
			smAllItems[j].style.KhtmlOpacity = smItemsFullOpacity / 100;
			smAllItems[j].style.filter = "alpha(opacity=" + smItemsFullOpacity + ")";
		}		
	}
}

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];
        }
      }
      continue; // Skip to next token
    }
    // 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;
}

String.prototype.trim=function(){
    return this.replace(/^\s*|\s*$/g,'');
}

function findCoord(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}