// Make a literal string safe to include in regex patterns
function encodeForRegEx(s) { 
  return s.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1') 
}

// Add css class 'selected' to relevant banner menu links
//
// Example: If the current page is: http://mysite.com/about-us/our-markets/education,
// we need to add the css class to any <li> elements that contain an anchor tag
// which points to: http://mysite.com/about-us, or http://mysite.com/about-us/our-markets,
// or http://mysite.com/about-us/our-markets/education
function setSelected( anchors, currentUrl ) {
  for ( var i=0; i < anchors.length; i++ ) {
    var escapedHref = encodeForRegEx( anchors[i].href );
    var regex = new RegExp( '^' + escapedHref + '$|^' + escapedHref + '\\/', 'i' );
    if ( regex.test( currentUrl ) ) {
      if ( anchors[i].parentNode.tagName != "DIV" ) { anchors[i].className += " selected"; }
    }
  }
}

// Pass the current page url and an array of all the 
// links within the banner menu to the setSelected function.
function highlightCurrentSection() {
  if ( document.getElementById( "bannerMenu" ) != null ) {
    var currentUrl = document.location.href ? document.location.href : document.location;
    currentUrl = currentUrl.replace(/\?.*/,''); // strip off any querystring parameters
    setSelected( document.getElementById( "bannerMenu" ).getElementsByTagName( "a" ), currentUrl ); 
  }
}

// Give IE a helping hand to enable hover like behaviour on <li> elements.
initBannerMenu = function() {
  var bmEls = document.getElementById( "bannerMenu" ).getElementsByTagName( "LI" );
  for ( var i=0; i<bmEls.length; i++ ) {
    bmEls[i].onmouseover=function() {
      this.className+=" bmhover";
    }
    bmEls[i].onmouseout=function() {
      this.className=this.className.replace( new RegExp( " bmhover\\b" ), "" );
    }
  }
}

// Attach function to highlight current page/section in banner menu
// + if we're running in IE, attach the required events for handling 
// hovering on <li> elements.
if ( window.addEventListener ) {
  window.addEventListener( "load", highlightCurrentSection, false ); 
} else if ( window.attachEvent ) {
  window.attachEvent( "onload", initBannerMenu );
  window.attachEvent( "onload", highlightCurrentSection);
}
