/*
  @file   megamenu.js
  @author Craig Waterman / @ckh2oman / craigwaterman@gmail.com
  
  Javascript to make the megamenus play nicely with the layout.
  We have to wait until Typekit finishes loading (or we reach the timeout)
  so the offset metrics are correct (the layout changes - FOUT)
  Using polling because linking up Typekit's "active" event from
  outside the jQuery event system is buggy cross-platform. *grumble IE*

*/

var typekitTimer = null;        // timer id
var typekitWaitDuration = 100;  // polling interval
var typekitTimeout = 7000;     // timeout period
var typekitWaitTime = 0;        // elapsed time waiting
var typekitLoadWithoutTK = true;// load the menus even without type kit?
var menuTimeout = null;         // timer id for auto-hiding menus
var menuTimeoutDuration = 750;  // amount of time until menus auto-hide
var usingTypekit = true;        // do we need to poll for Typekit?

$(document).ready( function() {
  if( usingTypekit ) {
    typekitTimer = setTimeout( pollTypekitClass, typekitWaitDuration );
  } else {
    initMegaMenu();
  }
});


function pollTypekitClass() {

  clearTimeout(typekitTimer);

  typekitWaitTime += typekitWaitDuration;

  if( typekitWaitTime > typekitTimeout ) {
    if( typekitLoadWithoutTK ) {
      initMegaMenu();
    } else {
      return; // timeout reached, ABORT!
    }
  }

  if( $("html").hasClass("wf-active") ) {
    initMegaMenu();
  } else {
    typekitTimer = setTimeout( pollTypekitClass, typekitWaitDuration );
  }

}

function initMegaMenu() {
  positionMegaMenu();
  $(window).resize(positionMegaMenu);
  $(".megamenu").hover( clearMegaMenuTimeout, exitMegaMenu );
  $("nav#primary a").hover( enterMegaMenu, exitMegaMenu );
}

function positionMegaMenu() {

  nav = $("nav#primary");
  pos = nav.offset();
  menus = $(".megamenu");

  menus.css("top", pos.top + nav.height() + "px").css("left", pos.left + "px");
  
}

function enterMegaMenu() {
  clearMegaMenuTimeout();
  hideMegaMenus();

  if( $(window).width() >= 1024 ) {
    menuId = "#megamenu_" + $(this).attr("id").split("_")[1];
    $(menuId).removeClass("hide");
  }

}


function exitMegaMenu() {
  menuTimeout = setTimeout( hideMegaMenus, menuTimeoutDuration );
}

function hideMegaMenus() {
  $(".megamenu").addClass("hide");
}

function clearMegaMenuTimeout() {
  clearTimeout( menuTimeout );
}

