/**********************************************************************
   Page load
 *********************************************************************/

function doPageLoad() {
   rolloverInit();
   preloadGlobalImages();
   setTimeout('initTopnav()', 500);
   stripe('dataTable', '#DFE5F2', '#FFFFFF');
}

/**********************************************************************
   Image rollovers
 *********************************************************************/

function isDefined(property) {
  return (typeof property != 'undefined');
}

var rolloverInitialized = false;
function rolloverInit() {
   if (!rolloverInitialized && isDefined(document.images)) {
      
      // get all images (including all <input type="image">s)
      // use getElementsByTagName() if supported
      var images = new Array();
      if (isDefined(document.getElementsByTagName)) {
         images = document.getElementsByTagName('img');
         var inputs = document.getElementsByTagName('input');
         for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type == 'image') {
               images[images.length] = inputs[i];
            }
         }
      }
      
      // otherwise, use document.images and document.forms collections
      // remove if not supporting IE4, Opera 4-5
      else {
         images = document.images;
         inputs = new Array();
         for (var formIndex = 0; formIndex < document.forms.length; formIndex++) {
            for (var elementIndex = 0; elementIndex < document.forms.elements.length; elementIndex++) {
               if (isDefined(document.forms.elements[i].src)) {
                  inputs[inputs.length] = document.forms.elements[i];
               }
            }
         }
      }
      
      // get all images with '_off.' in src value
      for (var i = 0; i < images.length; i++) {
         if (images[i].src.indexOf('_off.') != -1) {
            var image = images[i];
            
            // store the off state filename in a property of the image object
            image.offImage = new Image();
            image.offImage.src = image.src;
            
            // store the on state filename in a property of the image object
            // (also preloads the on state image)
            image.onImage = new Image();
            image.onImage.imageElement = image;
            
            // add onmouseover and onmouseout event handlers once the on state image has loaded
            // Safari's onload is screwed up for off-screen images; temporary fix
            if (navigator.userAgent.toLowerCase().indexOf('safari') != - 1) {
               image.onmouseover = function() {
                  this.src = this.onImage.src;
               };
               image.onmouseout = function() {
                  this.src = this.offImage.src;
               };
            }
            else {
               image.onImage.onload = function() {
                  this.imageElement.onmouseover = function() {
                     this.src = this.onImage.src;
                  };
                  this.imageElement.onmouseout = function() {
                     this.src = this.offImage.src;
                  };
               };
            }
            
            // set src of on state image after defining onload event handler
            // so cached images (that load instantly in IE) will trigger onload
            image.onImage.src = image.src.replace(/_off\./, '_on.');
         }
      }
   }
   rolloverInitialized = true;
}


/**********************************************************************
   Preload Images
 *********************************************************************/

function preloadGlobalImages() {
   var imageURLs = [];
   for (var imageIndex = 0; imageIndex < imageURLs.length; imageIndex++) {
      (new Image()).src = imageURLs[imageIndex];
   }
}


/**********************************************************************
   Topnav functionality
 *********************************************************************/

function initTopnav() {
   initTopnavItem( 'topnav-about-aiesec', 'topnav-about-aiesec-tier2');
   initTopnavItem('topnav-students', 'topnav-students-tier2');
   initTopnavItem('topnav-employers', 'topnav-employers-tier2');
   initTopnavItem('topnav-alumni', 'topnav-alumni-tier2');
   //initTopnavItem('topnav-advantage', 'topnav-advantage-tier2');
   initTopnavItem('topnav-networks', 'topnav-networks-tier2');
   initTopnavItem('topnav-contact-us', 'topnav-contact-us-tier2');
}

function initTopnavItem(topnavItemId, menuId) {
   var topnavItem = document.getElementById(topnavItemId);
   var menu = document.getElementById(menuId);
   
   if (topnavItem == null || menu == null) return;
   
   // add event handlers to topnav item
   topnavItem.menu = menu;
   topnavItem.onmouseover = showTopnavTier2;
   topnavItem.onmouseout = hideTopnavTier2;

   // position menu
   menu.style.left = topnavItem.offsetLeft + 'px';
   menu.style.top = topnavItem.offsetTop + topnavItem.firstChild.offsetHeight + 'px';
}

var currentMenu = null;
var hideMenuTimeout = null;

function showTopnavTier2(menu) {
   if (hideMenuTimeout) {
      clearTimeout(hideMenuTimeout);
      if (currentMenu && currentMenu != this.menu) {
         delayedHideTopnavTier2();
      }
   }
   this.menu.style.visibility = 'visible';
   currentMenu = this.menu;
}

function hideTopnavTier2() {
   hideMenuTimeout = setTimeout('delayedHideTopnavTier2()', 400);
}

function delayedHideTopnavTier2() {
   if (currentMenu) {
      currentMenu.style.visibility = 'hidden';
      currentMenu = null;
   }
}

/******************************************************************************
	Adding event listeners
 *****************************************************************************/

function addEventListenerToElement(element, eventType, functionValue, capture) {
	if (element.addEventListener) element.addEventListener(eventType, functionValue, capture);
	else if (element.attachEvent) element.attachEvent("on" + eventType, functionValue);
   else {
      if (!element['on' + eventType]) {
         element['on' + eventType] = function(e) {
            if (!e) e = event;
            var functionArray = eval('this.' + e.type + 'Handler');
            for (var index = 0; index < functionArray.length; index++) {
               if (functionArray[index] != null) {
                  functionArray[index](e);
               }
            }
         };
         element[eventType + 'Handler'] = new Array();
         // element[eventType + 'Handler'].element = this;
      }
      var index = 0;
      while (element[eventType + 'Handler'][index] != null) {
         index++;
      }
      element[eventType + 'Handler'][index] = functionValue;
   }
}

function addEventListenerToDescendants(element, eventType, functionValue, capture) {
   addEventListenerToElement(element, eventType, functionValue, capture);
   var childNodes = element.childNodes;
   for (var childIndex = 0; childIndex < childNodes.length; childIndex++) {
      var childNode = childNodes[childIndex]
      if (childNode.nodeType == 1) {
         addEventListenerToDescendants(childNode, eventType, functionValue, capture);
      }
   }
}

/**********************************************************************
   Alternate colours for table rows
   (see http://www.alistapart.com/articles/zebratables/)
 *********************************************************************/

  // this function is needed to work around 
  // a bug in IE related to element attributes
  function hasClass(obj) {
     var result = false;
     if (obj.getAttributeNode("class") != null) {
         result = obj.getAttributeNode("class").value;
     }
     return result;
  }   

 function stripe(id) {

    // the flag we'll use to keep track of 
    // whether the current row is odd or even
    var even = false;
  
    // if arguments are provided to specify the colours
    // of the even & odd rows, then use the them;
    // otherwise use the following defaults:
    var evenColor = arguments[1] ? arguments[1] : "#fff";
    var oddColor = arguments[2] ? arguments[2] : "#eee";
  
    // obtain a reference to the desired table
    // if no such table exists, abort
    var table = document.getElementById(id);
    if (! table) { return; }
    
    // by definition, tables can have more than one tbody
    // element, so we'll have to get the list of child
    // &lt;tbody&gt;s 
    var tbodies = table.getElementsByTagName("tbody");

    // and iterate through them...
    for (var h = 0; h < tbodies.length; h++) {
    
     // find all the &lt;tr&gt; elements... 
      var trs = tbodies[h].getElementsByTagName("tr");
      
      // ... and iterate through them
      for (var i = 0; i < trs.length; i++) {

        // avoid rows that have a class attribute
        // or backgroundColor style
        if (! hasClass(trs[i]) &&
            ! trs[i].style.backgroundColor) {
 		  
          // get all the cells in this row...
          var tds = trs[i].getElementsByTagName("td");
        
          // and iterate through them...
          for (var j = 0; j < tds.length; j++) {
        
            var mytd = tds[j];

            // avoid cells that have a class attribute
            // or backgroundColor style
            if (! hasClass(mytd) &&
                ! mytd.style.backgroundColor) {
        
              mytd.style.backgroundColor =
                even ? evenColor : oddColor;
            
            }
          }
        }
        // flip from odd to even, or vice-versa
        even =  ! even;
      }
    }
  }


/**********************************************************************
   Cleaning the DOM (for Mozilla)
   (see http://www.codingforums.com/showthread.php?t=7028)
 *********************************************************************/

var notWhitespace = /\S/;

function cleanWhitespace(node) {
   for (var x = 0; x < node.childNodes.length; x++) {
      var childNode = node.childNodes[x];
      
      // remove any whitespace text nodes
      if ( childNode.nodeType == 3 && !notWhitespace.test(childNode.nodeValue) ) {
         node.removeChild(node.childNodes[x]);
         x--;
      }
      
      // recurse thru any element nodes removing whitespace
      if (childNode.nodeType == 1) {
         cleanWhitespace(childNode);
      }
   }
}

