$(document).ready(function () {
  //For the initial navigation items to ensure the item is aligned correctly
  $("#hd-nav ul ul").addClass("hidden");

  $("#hd-nav > ul > li.dropdownmenu").hover(function () {
    var link = $(this).children("a");
    var subMenu = $(this).children("ul");
    var windowWidth = $(window).width();

    if (subMenu.length > 0) {
      $(this).addClass("hover");
      $(this).children("ul").removeClass("hidden");
      link.addClass("hover");

      var subMenuOffset = subMenu.offset().left;
      var parentOffset = $(this).offset().left;

      //Perform check to ensure it does not fit in the browser
      if (((subMenuOffset + subMenu.width()) > windowWidth)) {
        //position to the left
        subMenu.addClass("dropdownmenu-right");
      }
      //Perform check to ensure it would once again fit in the browser window
      else if ((parentOffset + $(this).width()) + subMenu.width() < windowWidth) {
        subMenu.removeClass("dropdownmenu-right");
      }
    }
  }, function () {
    $(this).removeClass("hover");
    $(this).children("ul").addClass("hidden");
    $(this).children("a").removeClass("hover");
  })

  //For the second and third level navigation items
  $("#hd-nav li li.parent").hover(function () {
    var link = $(this).children("a");
    var subMenu = $(this).children("ul");
    var windowWidth = $(window).width();

    if (subMenu.length > 0) {
      link.addClass("hover");
      $(this).addClass("hover");
      $(this).children("ul").removeClass("hidden");

      var subMenuOffset = subMenu.offset().left;
      var parentOffset = $(this).offset().left;

      //Perform check to ensure it does not fit in the browser
      if ((subMenuOffset + subMenu.width()) > windowWidth) {
        $(this).addClass("parent-right");
        subMenu.addClass("hover-right");

        if (subMenu.offset().left >= 0) {
          subMenu.css({ left: -(subMenu.width()) });
          subMenu.css({ right: "auto" });
        }
      }
      //Perform check to ensure it would once again fit in the browser window
      else if ((parentOffset + $(this).width()) + subMenu.width() < windowWidth) {
        $(this).removeClass("parent-right");
        subMenu.removeClass("hover-right");
        subMenu.removeAttr("style");
      }
    }
  }, function () {
    $(this).removeClass("hover");
    $(this).children("ul").addClass("hidden");
    $(this).children("a").removeClass("hover");
  })
});
