/*global document , window, navigator, location */ /*jslint indent: 2 */
(function () {
  "use strict";
  var lastidset = "", doattach = false, useeventlistener = false, hashused = false, locpath = location.pathname.substr(1);
  function setitalicid(idx) {
    var i, b = document.getElementsByTagName('b');
    lastidset = idx;
    for (i = 0; i < b.length; i += 1) {
      b[i].style.fontStyle = (b[i].id === idx) ? "italic" : "normal";
    }
  }
  function Setitalic(e) {
    if (hashused) {return; }
    var io, targ = this;
    if (doattach) {
      targ = e.srcElement;
      while (targ && targ.nodeName !== "A") {targ = targ.parentNode; }
      if (!targ || !targ.href) {return; }
    }
    io = targ.href.indexOf("#");
    if (io > -1) {
      setitalicid(targ.href.substr(io + 1));
    }
  }
  function setitalicload() {
    var winloc = window.location.hash, a = document.getElementsByTagName('a'), i;
    for (i = 0; i < a.length; i += 1) {
      if (a[i].hash && (a[i].pathname === location.pathname || a[i].pathname === locpath)) {
        if (useeventlistener) {
          a[i].addEventListener('click', Setitalic, false);
        } else if (doattach) {
          a[i].attachEvent('onclick', Setitalic);
        }
      }
    }
    if (winloc.substr(0, 1) === "#") {winloc = winloc.substr(1); }
    if (winloc) {setitalicid(winloc); }
  }
  function setitalichash() {
    var winloc = window.location.hash;
    hashused = true;
    if (winloc.substr(0, 1) === "#") {winloc = winloc.substr(1); }
    if (winloc && winloc !== lastidset) {setitalicid(winloc); }
  }
  if (document.getElementsByTagName) {
    if (window.addEventListener) {
      useeventlistener = true;
      window.addEventListener("load", setitalicload, false);
      window.addEventListener("hashchange", setitalichash, false);
    } else if (window.attachEvent) {
      if (navigator.userAgent.indexOf("MSIE 8") === -1) {
        doattach = true;
        window.attachEvent("onload", setitalicload);
      } else {
        window.attachEvent("onload", setitalicload);
        window.attachEvent("onhashchange", setitalichash);
      }
    }
  }
}());

