$(function() {

  if (typeof subNavData == 'undefined') {
    // Bail out if there's no content
    return;
  }

  var hideTimeout;

  // Replace static with dynamic subnav on hover
  $('#mainnav .main').hover(
    function() {
      var $$ = $(this);

      // Clear any dynamic subnavs
      clearTimeout(hideTimeout);
      $('#mainnav div.subnav_content_dynamic').hide();

      var $mainNavEntry = $$.children('.mainnav_entry_txt');
      if (!$mainNavEntry.size()) {
        // Show static subnav for the active entry
        $('#subnav_content > div').show();
        return;
      }
      var $subNav = $mainNavEntry.children('.subnav_content_dynamic');
      if (!$subNav.size()) {
        // Create the subnav if it doesn't exist yet
        newSubNav = createSubNav($$.attr('id'));
        if (newSubNav) {
          $subNav = $mainNavEntry.html($mainNavEntry.html() + newSubNav).children('.subnav_content_dynamic');
          // Stretch the container down to the mainnav entry
          $subNav.height(Math.max($$.offset().top - $('#mainnav').offset().top + $$.height(), $subNav.height()));
        }
      }
      // Hide static subnav
      $('#subnav_content > div').hide();
      // Position dynamic subnav over static one
      var offset = $('#subnav_content').offset();
      var frameOffset = $('#CFCToolBarDiv ~ div').offset();
      offset.top -= frameOffset ? frameOffset.top : 0;
      $subNav.css({ top: offset.top, left: offset.left }).show();
    },
    function() {
       hideTimeout = setTimeout(function() {
         // Hide dynamic subnav
         $('#mainnav div.subnav_content_dynamic').hide();
         // Show static subnav
         $('#subnav_content > div').show();
       }, 500);
    }
  );

  function createSubNav(pEntry) {
    if (pEntry && subNavData[pEntry]) {
      var newSubNav = '<div class="subnav_content_dynamic"><div class="subnav_linkblock">';
      // Insert the subnav links
      jQuery.each(subNavData[pEntry], function(pTitle, pAnchor) {
        newSubNav += '<div class="subnav_link">';
        if (pTitle) {
          if (pAnchor) {
            newSubNav += pAnchor;
          }
          newSubNav += '<img src="' + global_staticpath_images +'/arrow_grey.gif" width="9" height="9" alt="&gt;" class="arrow_subnav">';
          if (pAnchor) {
            newSubNav += '</a>' + pAnchor;
          }
          newSubNav += pTitle;
          if (pAnchor) {
            newSubNav += '</a>';
          }
        }
        newSubNav += '</div>';
      });
      newSubNav += '</div></div>';
      return newSubNav;
    }
  }

});

