$(document).ready(function () {
  
  var currentSelection;
  var currentSelectionVer;
  var allowVer;
  var verListSize;
  var listSize = $("#mainNav > li").size();
  var currentUrl = '';
  var widthDiff = 10;
  
  // = Image Preload ===================================================================
  /*$.fn.preload = function() { this.each(function(){ $('<img/>')[0].src = this; }); }
  $(['/images/nav_dropdown_arrow_off.png']).preload();*/
  // ===================================================================================
  
  function allowVertical() {
    if ($("#mainNav > li").eq(currentSelection).children("div").hasClass("sub") == true) {
      allowVer = true;
      $("#test").html("allowVir: " + allowVer);
      $("#mainNav > li").eq(currentSelection).children("a").children("img").attr("src","/images/nav_dropdown_arrow_on.png");
    } else {
      allowVer = false;
      $("#test").html("allowVir: " + allowVer);
    }
    
    currentSelectionVer = null;
    verListSize = null;
    $("#mainNav > li").eq(currentSelection).children("div").find(".itemhover").stop().removeClass("itemhover");
    $(".subnavHover").removeClass("subnavHover");
  }
  
  function allULs (menu) {
    (function($) {
      jQuery.fn.calcSubWidth = function() {
        rowWidth = 0;
        //Calculate row
        menu.find("ul").each(function() {          
          rowWidth += $(this).width()+(parseInt($(this).css("margin-left").replace("px", ""))*2);
        });
      };
    })(jQuery);
    
    if ( menu.find(".row").length > 0 ) { //If row exists...
      var biggestRow = 0;  
      //Calculate each row
      menu.find(".row").each(function() {                 
        $(this).calcSubWidth();
        //Find biggest row
        if(rowWidth > biggestRow) {
          biggestRow = rowWidth;
        }
      });
      //Set width
      menu.find(".sub").css({'width' :biggestRow});
      menu.find(".row:last").css({'margin':'0'});
      
    } else { //If row does not exist...
      
      menu.calcSubWidth();
      //Set Width
      if (menu.find(".sub").hasClass("sectorSub")) { } 
      else { menu.find(".sub").css({'width' : rowWidth+widthDiff}); }
      
    }
  }
    
  $(document).keydown(function (event) {
    
    // Prevent page scrolling
    if(allowVer == true) {
        event.preventDefault();
    }
    
    // Left Arrow ---------------------------------------------------------------------------------------------------
    if (event.keyCode == 37) {
      if (currentSelection != null) {
        currentSelection--;
      } else {
        currentSelection = 0;
      }
      
      if (currentSelection == -1) {
        currentSelection = listSize-1;
        $("#mainNav > li").eq(currentSelection).find(".sub").stop().fadeTo('fast', 1).show();
        allULs($("#mainNav > li").eq(currentSelection));
        $("#mainNav > li").eq(currentSelection).addClass("itemhover");
        //$("#mainNav > li").eq(currentSelection).children("a").css({"color":"#333333","line-height":"33px"});
        
        $("#mainNav > li").eq(0).find(".sub").stop().fadeTo('fast', 0, function() { $(this).hide(); });
        $("#mainNav > li").eq(0).removeClass("itemhover");
        //$("#mainNav > li").eq(0).children("a").removeAttr("style");
        $("#mainNav > li").eq(0).children("a").children("img").attr("src","/images/nav_dropdown_arrow_off.png");
      } else {
        $("#mainNav > li").eq(currentSelection).find(".sub").stop().fadeTo('fast', 1).show();
        allULs($("#mainNav > li").eq(currentSelection));
        $("#mainNav > li").eq(currentSelection).addClass("itemhover");
        //$("#mainNav > li").eq(currentSelection).children("a").css({"color":"#333333","line-height":"33px"});
        
        $("#mainNav > li").eq(currentSelection+1).find(".sub").stop().fadeTo('fast', 0, function() { $(this).hide(); });
        $("#mainNav > li").eq(currentSelection+1).removeClass("itemhover");
        //$("#mainNav > li").eq(currentSelection+1).children("a").removeAttr("style");
        $("#mainNav > li").eq(currentSelection+1).children("a").children("img").attr("src","/images/nav_dropdown_arrow_off.png");
      }
      
      currentUrl = $("#mainNav > li").eq(currentSelection).find("a").stop().attr("href");
      allowVertical();
      
    // Right Arrow ---------------------------------------------------------------------------------------------      
    } else if (event.keyCode == 39) {
      if (currentSelection != null) {
        currentSelection++;
      } else {
        currentSelection = 0;
      }
      
      if (currentSelection == listSize) {
        currentSelection = 0;
        $("#mainNav > li").eq(currentSelection).find(".sub").stop().fadeTo('fast', 1).show();
        allULs($("#mainNav > li").eq(currentSelection));
        $("#mainNav > li").eq(currentSelection).addClass("itemhover");
        //$("#mainNav > li").eq(currentSelection).children("a").css({"color":"#333333","line-height":"33px"});
        
        $("#mainNav > li").eq(listSize-1).find(".sub").stop().fadeTo('fast', 0, function() { $(this).hide(); });
        $("#mainNav > li").eq(listSize-1).removeClass("itemhover");
        //$("#mainNav > li").eq(listSize-1).children("a").removeAttr("style");
        $("#mainNav > li").eq(listSize-1).children("a").children("img").attr("src","/images/nav_dropdown_arrow_off.png");
      } else {
        $("#mainNav > li").eq(currentSelection).find(".sub").stop().fadeTo('fast', 1).show();
        allULs($("#mainNav > li").eq(currentSelection));
        $("#mainNav > li").eq(currentSelection).addClass("itemhover");
        //$("#mainNav > li").eq(currentSelection).children("a").css({"color":"#333333","line-height":"33px"});
      
        $("#mainNav > li").eq(currentSelection-1).find(".sub").stop().fadeTo('fast', 0, function() { $(this).hide(); });
        $("#mainNav > li").eq(currentSelection-1).removeClass("itemhover");
        //$("#mainNav > li").eq(currentSelection-1).children("a").removeAttr("style");
        $("#mainNav > li").eq(currentSelection-1).children("a").children("img").attr("src","/images/nav_dropdown_arrow_off.png");
      }
      
      currentUrl = $("#mainNav > li").eq(currentSelection).find("a").stop().attr("href");
      allowVertical();
      
    // Up Arrow -------------------------------------------------------------------------------------------------
    } else if (event.keyCode == 38) {
      if (allowVer == true) {
        verListSize = $("#mainNav > li").eq(currentSelection).children("div").find("li").stop().size();
        if (currentSelectionVer != null) {
          currentSelectionVer--;
        } else {
          currentSelectionVer = 0;
        }
        
        if (currentSelectionVer == -1) {
          currentSelectionVer = verListSize-1;
          $("#mainNav > li").eq(currentSelection).children("div").find("a").eq(currentSelectionVer).stop().addClass("subnavHover");
          $("#mainNav > li").eq(currentSelection).children("div").find("a").eq(0).stop().removeClass("subnavHover");  
        } else {
          $("#mainNav > li").eq(currentSelection).children("div").find("a").eq(currentSelectionVer).stop().addClass("subnavHover");
          $("#mainNav > li").eq(currentSelection).children("div").find("a").eq(currentSelectionVer+1).stop().removeClass("subnavHover");
        }
        
        currentUrl = $("#mainNav > li").eq(currentSelection).children("div").find("a").eq(currentSelectionVer).stop().attr("href");
        $("#test").html("currentSelectionVer: " + currentSelectionVer);
      }
      
    // Down Arrow -------------------------------------------------------------------------------------------------
    } else if (event.keyCode == 40) {
      if (allowVer == true) {
        verListSize = $("#mainNav > li").eq(currentSelection).children("div").find("li").stop().size();
        if (currentSelectionVer != null) {
          currentSelectionVer++;
        } else {
          currentSelectionVer = 0;
        }
        
        if (currentSelectionVer == verListSize) {
          currentSelectionVer = 0;
          $("#mainNav > li").eq(currentSelection).children("div").find("a").eq(currentSelectionVer).stop().addClass("subnavHover");
          $("#mainNav > li").eq(currentSelection).children("div").find("a").eq(verListSize-1).stop().removeClass("subnavHover");  
        } else {
          $("#mainNav > li").eq(currentSelection).children("div").find("a").eq(currentSelectionVer).stop().addClass("subnavHover");
          $("#mainNav > li").eq(currentSelection).children("div").find("a").eq(currentSelectionVer-1).stop().removeClass("subnavHover");
        }
        
        currentUrl = $("#mainNav > li").eq(currentSelection).children("div").find("a").eq(currentSelectionVer).stop().attr("href");
        $("#test").html("currentSelectionVer: " + currentSelectionVer);
      }
    } else if (event.keyCode == 13) {
      if(currentUrl != '') {
        window.location = currentUrl;
      }
    } else if (event.keyCode == 27) {
       escapeNav();
    }
  });
    
    $(document).click(function() {
      if(allowVer == true) {
         escapeNav();
      }
    });
    
    function escapeNav() {
      $(".itemhover").children("a").removeAttr("style");
      $(".itemhover").removeClass("itemhover");
      $("#mainNav > li").eq(currentSelection).find(".sub").stop().fadeTo('fast', 0, function() {
        $(this).hide();
      });
      
      currentUrl = null;
      currentSelection = null;
      currentSelectionVer = null;
      allowVer = null;
    }
  
  //---------------------------------------------------------------------------
  
  function megaHoverOver(){
    //$(this).children("a").addClass("hover");
    $(".itemhover").children("a").removeAttr("style");
    $(".itemhover").removeClass("itemhover");
    $(".subnavHover").removeClass("subnavHover");
    if (currentSelection != null) {
      $("#mainNav > li").eq(currentSelection).find(".sub").stop().hide();
      currentSelection = null;
      currentSelectionVer = null;
    }
    /*$("#mainNav").mouseover(function() {
      $("#mainNav li .sub").hide();
    });*/
                                         
    $(this).find(".sub").stop().fadeTo("fast", 1, function() {}).show();
    
    if ($(this).children("div").hasClass("sub")) {
      $(this).children("a").children("span.navBottomArrow").addClass("navBottomArrow_green");
    }
      
    //Calculate width of all ul's
    (function($) {
      jQuery.fn.calcSubWidth = function() {
        rowWidth = 0;
        //Calculate row
        $(this).find("ul").each(function() {          
          rowWidth += $(this).width()+(parseInt($(this).css("margin-left").replace("px", ""))*2);
        });  
      };
    })(jQuery);
    
    if ( $(this).find(".row").length > 0 ) { //If row exists...
      var biggestRow = 0;  
      //Calculate each row
      $(this).find(".row").each(function() {                 
        $(this).calcSubWidth();
        //Find biggest row
        if(rowWidth > biggestRow) {
          biggestRow = rowWidth;
        }
      });
      //Set width
      $(this).find(".sub").css({'width' :biggestRow});
      $(this).find(".row:last").css({'margin':'0'});
    } else { //If row does not exist...
      
      $(this).calcSubWidth();
      //Set Width
      if ($(this).find(".sub").hasClass("sectorSub")) { } 
      else { $(this).find(".sub").css({'width' : rowWidth+widthDiff}); }
    }
  }
  
  function megaHoverOut(){
    if ($(this).children("div").hasClass("sub")) {
      $(this).children("a").children("span.navBottomArrow").removeClass("navBottomArrow_green"); 
    }
    
    $(this).children(".sub").stop().fadeTo(1, 0, function() {
      $('.sectorNavBlock').hide();
      $(".sectorNavFirstBlock").show();
      $(this).hide();
    });
  }
  
  if ($.browser.msie && $.browser.version <= 7) {
    $("#mainNav").hover(
      function () { $(".wincantonContent").css("position","relative").css("z-index","-1"); }, 
      function () { $(".wincantonContent").removeAttr("style"); }
    );
    
    $("#topNav").hover(
      function () { $(".wincantonContent, #header, body div.clear").css("position","relative").css("z-index","-1"); }, 
      function () { $(".wincantonContent, #header").removeAttr("style"); }
    );
  }

  var config = {    
     sensitivity: 5, // number = sensitivity threshold (must be 1 or higher)    
     interval: 1, // number = milliseconds for onMouseOver polling interval    
     over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
     timeout: 10, // number = milliseconds delay before onMouseOut    
     out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
  };

  $("ul#mainNav li .sub").css({'opacity':'0'});
  $("ul#mainNav li").hoverIntent(config);
  $("ul#topNav li").hoverIntent(config);
  
  //---------------------------------------------------------------------------
  
  
});

