// 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 anchor tags within an <li> that point 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 == "LI" ) { 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( "bm" ) != null ) {
    var currentUrl = document.location.href ? document.location.href : document.location;
    currentUrl = currentUrl.replace(/\?.*/,''); // strip off any querystring parameters
    setSelected( document.getElementById( "bm" ).getElementsByTagName( "a" ), currentUrl ); 
  }
}

// Give IE a helping hand to enable hover like behaviour on <li> elements.
initBannerMenu = function() {
  var bmEls = document.getElementById( "bm" ).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" ), "" );
    }
  }
}

// Add 'Search' text value label to search box
function searchBoxDefault() {

  var searchBox = document.getElementById( 'search_query' );
  var searchBoxText = 'Search';

  if ( !searchBox ) { return }

  if ( searchBox.value == '' || searchBox.value == searchBoxText ) {
    searchBox.style.color = '#ccc';
    searchBox.value = searchBoxText; 
  }

  searchBox.onfocus = function() {
    searchBox.style.color = '#3e3e3e';
    if ( searchBox.value == searchBoxText ) { searchBox.value = ''; }
  }

  searchBox.onblur = function() {
    if ( searchBox.value == '' ) {
      searchBox.style.color = '#ccc';
      searchBox.value = searchBoxText;
    }
  };

}

if ( window.addEventListener ) {
  window.addEventListener( "load", highlightCurrentSection, false ); 
  window.addEventListener( "load", searchBoxDefault, false ); 
} else if ( window.attachEvent ) {
  window.attachEvent( "onload", initBannerMenu );
  window.attachEvent( "onload", highlightCurrentSection);
  window.attachEvent( "onload", searchBoxDefault );
}

