var slideHeightLevel2 = "70px";
var slideHeightLevel3 = "105px";
var currentLevel2Menu = "";
var currentLevel3Menu = "";

var menuL2Open = false;
var menuL3Open = false;
var focusSetByHover = false;
var leftMenuOpen = false;

var numberOfL2Rows = 2; /* typical value */
var slideSpeed3 = 400;
var slideSpeed2 = 300;
var totalSpeed = 1000;

var hideInProgress = false;

var firstMenuElmPos = 0;

var spaceWidth = 0;

$(document).ready(function() {
    
    if ($.browser.mozilla) {
        spaceWidth = 11;
    }
    if ($.browser.msie) {
        spaceWidth = 11;
        if ($.browser.version==7.0) {
            spaceWidth = 14;
        }
    }     
    var menuWidth = spaceWidth;
    $('#MainMenu'+" > li").each( function() {
        menuWidth += $(this).outerWidth();
    });
    $('#MainMenu').css("width", menuWidth+"px");

    $('#MenuLevels').show();    
    addEventHandlers();
    preload();

    firstMenuElmPos = $("#MainMenu li:first").position().left;    
});

function preload() {
    var urls = [ 'Hydro_logo', 'addButton', 'addButton_mouseover', 'blue_sphere', 'border', 'breadcrumb_divider', 'breadcrumb_divider_last', 'bullet', 'contact_icon', 'customer_portal', 'customer_portal_mouseover',
                'deleteButton', 'deleteButton_mouseover', 'document', 'downloadButton', 'downloadButton_mouseover', 'download_arrow', 'download_arrow_mouseover', 'event', 'external_link', 'find_button', 'footer_line',
                'global_searchbutton', 'global_searchbutton_mouseover', 'global_searchbutton_pressed', 'global_searchfield', 'green_bullets', 'green_button', 'green_button_mouseover',
                'greensirkel', 'green_sphere', 'greysirkel', 'hyphen', 'landing_page_fnus', 'landing_page_fnus_white',
                'left', 'left_mouseover', 'level5', 'liten_fnus', 'L5_bottom', 'L5_bottom_selected', 'L5_middle', 'L5_middle_selected', 'L5_top', 'L5_top_selected',
                'main_menu', 'market', 'mediadoc', 'menu_blue_line', 'menu_container_line', 'menu_green_line', 'orange_sphere',
                'pdfIcon', 'print', 'print_mouseover', 'products_MagnifySearch', 'products_SearchField', 'productsearch_field', 'productsearch_button', 'right', 'right_mouseover', 'searchbutton', 'searchfield',
                'selected_elm_level1', 'selected_elm_level2','selected_elm_level2_big', 'selected_elm_level3', 'selected_elm_level1_liten', 'send_button',
                'sendmail', 'sendmail_mouseover', 'shade_blue', 'shade_green', 'sitemap_pil', 'sok_mouseover', 'sok_mouseover_grey', 'sok_pressed', 'sok_pressed_grey', 'whiteborder', 'white_sphere'];
    $.preload( urls, {
        base: '/TemplatesV2/images/',
        ext: '.png'
    });
}

function unselectMainMenuElements() {
        $('.MainMenuElement').css({
            fontWeight: "normal",
            backgroundImage: "url('/TemplatesV2/images/main_menu.png')",
            backgroundRepeat: "repeat-x",
            backgroundColor: "white",
            backgroundPosition: "bottom",
            borderTopColor: "white",
            borderTopStyle: "solid",
            borderTopWidth: "3px"
        });
    
        $('.ActiveMainMenuElement').css("border-top-color", "#0099cc");
}

function setActiveMainMenuElement(name) {
        var currentsClass = $(name).attr('css');
        if (currentsClass != '.ActiveMainMenuElement') {
            $('.ActiveMainMenuElement').css("border-top-color", "white");
        }
        else if (currentsClass == ".ActiveMainMenuElement"){
            $('.ActiveMainMenuElement').css("border-top-color", "#0099cc");
        }

        var menuId = name;
        $(menuId).css({
            fontWeight: "bold",
            borderTopColor: "#0099cc",
            borderTopStyle: "solid",
            borderTopWidth: "3px",
            borderBottom: "none",
            backgroundImage: "none"
        });
}

function unselectMenuLevel2Elements() {
        $('.MainMenuLevel2 .MenuElement').css("background-image", "none");
        $('.MainMenuLevel2 .MenuElementWithSubmenu').css({
            backgroundImage: "none",
            overflow: "hidden"
        });
}

function showMenuButton(menuId) {
        unselectMenuLevel2Elements();
        if ($(menuId).find('span').height() > 20) {
            $(menuId).css({
                height: "43px",
                backgroundImage: "url('/TemplatesV2/images/selected_elm_level2_big.png')"
            });
        }
        else {
            $(menuId).css("background-image", "url('/TemplatesV2/images/selected_elm_level2.png')");
        }
        $(menuId).css("background-repeat", "no-repeat");      
}

function showLevel2() {
        if (menuL3Open) {
            $(currentLevel3Menu).css({display: "block", height: slideHeightLevel3, overflow: "hidden"});
            $(currentLevel3Menu).animate({
                height: 0
            }, 500, function(){$(currentLevel3Menu).css({display:"none"}); menuL3Open = false;});
            $('#MainMenuLevel3Container').slideUp('slow', function() {
                // Animation complete.
            });
        }
        unselectMenuLevel2Elements();
        unselectMainMenuElements();
        setActiveMainMenuElement('#'+$(this).attr('id'));

        var menuWidth = spaceWidth;        
        $('#MainMenu'+" > li").each( function() {
            menuWidth += $(this).outerWidth();
        });
        $('#MainMenu').css("width", menuWidth+"px");

        currentLevel2Menu = '#'+$(this).attr('id')+'_menu';

        var currentHeight = slideHeightLevel2;
        setSlideHeightLevel2();

        // Due to flexible menu widths, we set the level2 position here.
        var margin = $(this).position().left - firstMenuElmPos;
        $(currentLevel2Menu).css("margin-left", "-"+margin+"px");

        $(".MainMenuLevel3").css({display: "none", height: 0 });
        $(".MainMenuLevel2").css({display: "none", height: 0 });

        if (!menuL2Open) {
            $('#MenuLevels').show();

            $(currentLevel2Menu).css({display: "block", height: 0, overflow: "hidden"});
            $('#MainMenuLevel2Container').css("height", slideHeightLevel2);
            $('#MainMenuLevel2Container').slideDown('slow', function() {
                // Animation complete.
            });
            $(currentLevel2Menu).animate({
                height: slideHeightLevel2

            }, 700, function(){$(currentLevel2Menu).css({overflow:"visible"}); menuL2Open = true;});
        }
        else {
            if (currentHeight != slideHeightLevel2) {
                $('#MainMenuLevel2Container').animate({height:slideHeightLevel2}, 'slow');
                $(currentLevel2Menu).css({display: "block", height: currentHeight, overflow: "hidden"});
                $(currentLevel2Menu).animate({
                    height: slideHeightLevel2
                }, 500, function(){$(currentLevel2Menu).css({overflow:"visible"});});
            }
            else {
                $(currentLevel2Menu).css({display: "block", height: slideHeightLevel2, overflow: "visible"});
            }
        }
        focusSetByHover = true;
        $(this).children()[0].focus();
}

function hideMenus() {
        if (hideInProgress) {
            return;
        }
        hideInProgress = true;
        unselectMainMenuElements();
        unselectMenuLevel2Elements();
        if (menuL3Open && menuL2Open) {
            $(currentLevel3Menu).css({display: "block", height: slideHeightLevel3, overflow: "hidden"});
            $(currentLevel3Menu).animate({
                height: 0
            }, slideSpeed3, function(){
                menuL3Open = false;
                $(currentLevel3Menu).css({display:"none"});
                $(currentLevel2Menu).css({display: "block", height: slideHeightLevel2, overflow: "hidden"});
                $(currentLevel2Menu).animate({
                    height: 0
                }, slideSpeed2, function(){$(currentLevel2Menu).css({display:"none"}); menuL2Open = false; hideInProgress = false;});
            });          
            $('#MenuLevels').slideUp(totalSpeed, function() {
                $('#MainMenuLevel3Container').css({
                    display: "none",
                    height: 0
                });
                $('#MainMenuLevel2Container').css({
                    display: "none",
                    height: 0
                });
                hideInProgress = false;
            });
        }
        else if (menuL2Open) {
            $(currentLevel2Menu).css({display: "block", height: slideHeightLevel2, overflow: "hidden"});
            $(currentLevel2Menu).animate({
                height: 0
            }, 500, function(){$(currentLevel2Menu).css({display:"none"}); menuL2Open = false; hideInProgress = false;});
            $('#MainMenuLevel2Container').slideUp('slow', function() {
                // Animation complete.
                hideInProgress = false;
            });
        }
}

function setSlideHeightLevel2() {
    $(currentLevel2Menu).css({display: "block"});    
    var twoLinerL2 = false;
    $(currentLevel2Menu).find('.MenuElementWithSubmenu span').each( function() {
        if ($(this).height() > 20) {
            $(this).parent().parent().addClass("TwoLiner");
            $(this).parent().parent().addClass("WithSubmenu");
            twoLinerL2 = true;
        }
    });
    $(currentLevel2Menu).find('.MenuElement').each( function() {
        if ($(this).find('span').height() > 20) {
            $(this).parent().parent().addClass("TwoLiner");
            twoLinerL2 = true;
        }
    });

    var rowHeightL2 = 35;
    var newHeightL2 = 0;

    if (twoLinerL2) {       
       $(currentLevel2Menu+" > li").each( function() { // We do only search for li elm on menu level 2, not 3.
            if (!$(this).is(".TwoLiner")) {
                $(this).addClass("inTwoLinerRow");
            }
        });
        rowHeightL2 = 43;
    }

    var numberOfMenuElements = $(currentLevel3Menu).find('li').size();
    
    numberOfMenuElements = $(currentLevel2Menu+" > li").size();
    if (numberOfMenuElements < 5) {
        numberOfL2Rows = 1;
        slideHeightLevel2 = newHeightL2 + rowHeightL2; //35;
        var level3Position = slideHeightLevel2+10+"px";
        // We adjust the positioning of menu level 3 based on the number of rows on level 2
        $(".MainMenuLevel3.FirstRowFirstColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.FirstRowSecondColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.FirstRowThirdColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.FirstRowFourthColumn").css("margin-top", level3Position);
    }
    else if (numberOfMenuElements < 9) {
        numberOfL2Rows = 2;
        slideHeightLevel2 = newHeightL2 + 2*rowHeightL2; //70;
        var level3PositionFirstRow = slideHeightLevel2+10+"px";
        level3Position = slideHeightLevel2-rowHeightL2+10+"px";
        
        $(".MainMenuLevel3.FirstRowFirstColumn").css("margin-top", level3PositionFirstRow);
        $(".MainMenuLevel3.FirstRowSecondColumn").css("margin-top", level3PositionFirstRow);
        $(".MainMenuLevel3.FirstRowThirdColumn").css("margin-top", level3PositionFirstRow);
        $(".MainMenuLevel3.FirstRowFourthColumn").css("margin-top", level3PositionFirstRow);

        $(".MainMenuLevel3.SecondRowFirstColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.SecondRowSecondColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.SecondRowThirdColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.SecondRowFourthColumn").css("margin-top", level3Position);
    }
    else if (numberOfMenuElements < 13) {
        numberOfL2Rows = 3;
        slideHeightLevel2 = newHeightL2 + 3*rowHeightL2; //105;
        level3PositionFirstRow = slideHeightLevel2+10+"px";
        var level3PositionSecondRow = slideHeightLevel2-rowHeightL2+10+"px"; //35
        level3Position = slideHeightLevel2-2*rowHeightL2+10+"px"; //70

        $(".MainMenuLevel3.FirstRowFirstColumn").css("margin-top", level3PositionFirstRow);
        $(".MainMenuLevel3.FirstRowSecondColumn").css("margin-top", level3PositionFirstRow);
        $(".MainMenuLevel3.FirstRowThirdColumn").css("margin-top", level3PositionFirstRow);
        $(".MainMenuLevel3.FirstRowFourthColumn").css("margin-top", level3PositionFirstRow);

        $(".MainMenuLevel3.SecondRowFirstColumn").css("margin-top", level3PositionSecondRow);
        $(".MainMenuLevel3.SecondRowSecondColumn").css("margin-top", level3PositionSecondRow);
        $(".MainMenuLevel3.SecondRowThirdColumn").css("margin-top", level3PositionSecondRow);
        $(".MainMenuLevel3.SecondRowFourthColumn").css("margin-top", level3PositionSecondRow);

        $(".MainMenuLevel3.ThirdRowFirstColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.ThirdRowSecondColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.ThirdRowThirdColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.ThirdRowFourthColumn").css("margin-top", level3Position);
    }
    else if (numberOfMenuElements < 17) {
        numberOfL2Rows = 4;
        slideHeightLevel2 = newHeightL2 + 4*rowHeightL2; //140;

        level3PositionFirstRow = slideHeightLevel2+10+"px";
        level3PositionSecondRow = slideHeightLevel2-rowHeightL2+10+"px"; //35
        var level3PositionThirdRow = slideHeightLevel2-2*rowHeightL2+10+"px"; //70
        level3Position = slideHeightLevel2-3*rowHeightL2+10+"px"; //105

        $(".MainMenuLevel3.FirstRowFirstColumn").css("margin-top", level3PositionFirstRow);
        $(".MainMenuLevel3.FirstRowSecondColumn").css("margin-top", level3PositionFirstRow);
        $(".MainMenuLevel3.FirstRowThirdColumn").css("margin-top", level3PositionFirstRow);
        $(".MainMenuLevel3.FirstRowFourthColumn").css("margin-top", level3PositionFirstRow);

        $(".MainMenuLevel3.SecondRowFirstColumn").css("margin-top", level3PositionSecondRow);
        $(".MainMenuLevel3.SecondRowSecondColumn").css("margin-top", level3PositionSecondRow);
        $(".MainMenuLevel3.SecondRowThirdColumn").css("margin-top", level3PositionSecondRow);
        $(".MainMenuLevel3.SecondRowFourthColumn").css("margin-top", level3PositionSecondRow);

        $(".MainMenuLevel3.ThirdRowFirstColumn").css("margin-top", level3PositionThirdRow);
        $(".MainMenuLevel3.ThirdRowSecondColumn").css("margin-top", level3PositionThirdRow);
        $(".MainMenuLevel3.ThirdRowThirdColumn").css("margin-top", level3PositionThirdRow);
        $(".MainMenuLevel3.ThirdRowFourthColumn").css("margin-top", level3PositionThirdRow);

        $(".MainMenuLevel3.FourthRowFirstColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.FourthRowSecondColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.FourthRowThirdColumn").css("margin-top", level3Position);
        $(".MainMenuLevel3.FourthRowFourthColumn").css("margin-top", level3Position);
    }    

}

function setSlideHeightLevel3() {
        $(currentLevel3Menu).css("display", "block"); // To make this menu readable.
        var twoLiner = false;
        $(currentLevel3Menu).find('span').each( function() {
            if ($(this).height() > 20) {
                $(this).parent().parent().addClass("TwoLiner");              
                twoLiner = true;
            }
        });

        var rowHeight = 35;

        if (twoLiner) {
            $(currentLevel3Menu).find('li').each( function() {
                if (!$(this).is(".TwoLiner")) {
                    $(this).addClass("inTwoLinerRow");
                }
            });
            rowHeight = 43;
        }
 
        var numberOfMenuElements = $(currentLevel3Menu).find('li').size();       
        var newHeight = 0; 

        if (numberOfMenuElements < 5) {
            newHeight += rowHeight;
            totalSpeed = 800;
            slideSpeed3 = 150;
            switch (numberOfL2Rows) {
                case 1: slideSpeed2 = 200;
                case 2: slideSpeed2 = 200;
                case 3: slideSpeed2 = 300; totalSpeed = 1000;
                case 4: slideSpeed2 = 400; totalSpeed = 1000;
            }
        }
        else if (numberOfMenuElements < 9) {
            newHeight += 2*rowHeight;            
            slideSpeed3 = 300;
            totalSpeed = 900;
            switch (numberOfL2Rows) {
                case 1: slideSpeed2 = 250;
                case 2: slideSpeed2 = 250;
                case 3: slideSpeed2 = 300; totalSpeed = 1100;
                case 4: slideSpeed3 = 200; slideSpeed2 = 400; totalSpeed = 1200;
            }          
        }
        else if (numberOfMenuElements < 13) {
            newHeight += 3*rowHeight;            
            slideSpeed3 = 400;           
            totalSpeed = 1000;
            switch (numberOfL2Rows) {
                case 1: slideSpeed2 = 300;
                case 2: slideSpeed2 = 300;
                case 3: slideSpeed2 = 400; totalSpeed = 1100;
                case 4: slideSpeed3 = 300; slideSpeed2 = 500; totalSpeed = 1300;
            }            
        }
        else if (numberOfMenuElements < 17) {
            newHeight += 4*rowHeight;            
            slideSpeed3 = 450;
            totalSpeed = 1100;
            switch (numberOfL2Rows) {
                case 1: slideSpeed2 = 400;
                case 2: slideSpeed2 = 400;
                case 3: slideSpeed2 = 450; totalSpeed = 1100;
                case 4: slideSpeed3 = 300; slideSpeed2 = 600; totalSpeed = 1300;
            }            
        }
        
        slideHeightLevel3 = newHeight;
}

function showLevel3Content() {
        $(currentLevel3Menu).css({display: "block", height: slideHeightLevel3, overflow: "hidden"});
        $(currentLevel3Menu).animate({
            height: 0
        }, 500, function(){$(currentLevel3Menu).css({display:"none"}); menuL3Open = false;});
        $('#MainMenuLevel3Container').slideUp('slow', function() {
            // Animation complete.
        });
}

function closeLevel2(){
        unselectMenuLevel2Elements();
        $(currentLevel2Menu).css({display: "block", height: slideHeightLevel2, overflow: "hidden"});
        $(currentLevel2Menu).animate({
            height: 0
        }, 500, function(){$(currentLevel2Menu).css({display:"none"}); menuL2Open = false;});
        $('#MainMenuLevel2Container').slideUp('slow', function(){
            // Animation complete.
        });
}

function openLevel2(){
        $('#MenuLevels').show();
        setSlideHeightLevel2();        
        $('#MainMenuLevel2Container').css("height", slideHeightLevel2);
        $('#MainMenuLevel2Container').slideDown('slow', function() {
            // Animation complete.
        });
        $(currentLevel2Menu).css({display: "block", height: 0, overflow: "hidden"});
        $(currentLevel2Menu).animate({
            height: slideHeightLevel2

        }, 700, function(){$(currentLevel2Menu).css({overflow:"visible"}); menuL2Open = true;});
}

function openLevel3(){
        setSlideHeightLevel3(); 
        $('#MainMenuLevel3Container').css("height", slideHeightLevel3);
        $('#MainMenuLevel3Container').slideDown('slow', function() {
            // Animation complete
        });
        $(currentLevel3Menu).css({display: "block", height: 0, overflow: "hidden"}); 
        $(currentLevel3Menu).animate({
            height: slideHeightLevel3
        }, 700, function(){menuL3Open = true;});
}

function showLevel2Content(){
        $(".MainMenuLevel3").css({display: "none", height: 0 });
        $(".MainMenuLevel2").css({display: "none", height: 0 });
        unselectMenuLevel2Elements();

        $(currentLevel2Menu).css({display: "block", height: slideHeightLevel2, overflow: "visible"});

        var currentHeight = slideHeightLevel2;
        setSlideHeightLevel2();
        if (currentHeight != slideHeightLevel2) {
            $('#MainMenuLevel2Container').animate({height:slideHeightLevel2}, 'slow');
            $(currentLevel2Menu).css({display: "block", height: currentHeight, overflow: "hidden"});
            $(currentLevel2Menu).animate({
                height: slideHeightLevel2
            }, 500, function(){$(currentLevel2Menu).css({overflow:"visible"});});
        }
        else {
            $(currentLevel2Menu).css({display: "block", height: slideHeightLevel2});
        }
}

function addEventHandlers(){

    // Necessary for touch devices, like iPad. 
    $('#MainContent').bind({click: function() {hideMenus();}});
    $('#HeaderTop').bind({click: function() {hideMenus();}});
    
    // Main menu mouse over effects:
    $("#MenuContainer").hoverIntent(function(){}, hideMenus);

    $(".MainMenuElement").hoverIntent(showLevel2, function(){});

    $(".ActiveMainMenuElement").hoverIntent(showLevel2, function(){});

    $(".MenuElement").hoverIntent(function(){
        unselectMenuLevel2Elements();
        showMenuButton('#'+$(this).parent().attr("id")+' .MenuElement');
        if (menuL3Open) {
            showLevel3Content();
        }  
        $(this)[0].focus();
    }, function(){});
    
    $(".MenuElementWithSubmenu").hoverIntent(function(){
        unselectMenuLevel2Elements();
        showMenuButton('#'+$(this).parent().attr("id")+' .MenuElementWithSubmenu');

        $(".MainMenuLevel3").css({ display: "none", height: 0 });
        currentLevel3Menu = '#'+$(this).parent().attr("id")+'_menu';
        
        var currentHeight = slideHeightLevel3;
        setSlideHeightLevel3();

        if (!menuL3Open ){
            $(currentLevel3Menu).css({display: "block", height: 0, overflow: "hidden"});
            openLevel3(); 
        }
        else if (currentHeight != slideHeightLevel3) {
            $(currentLevel3Menu).css({display: "block", height: currentHeight, overflow: "hidden"});
            $('#MainMenuLevel3Container').animate({height:slideHeightLevel3}, 'slow');
            $(currentLevel3Menu).animate({
                height: slideHeightLevel3
            }, 500);

        }
        else {
            $(currentLevel3Menu).css({display: "block", height: slideHeightLevel3});
        }
        focusSetByHover = true;
        $(this)[0].focus();
            
    }, function(){        
    });

    // Accessibility (traversing main menu by keys):
    $('.MainMenuElement').keydown(function(e) {
        var code = e.which;
        var shift = e.shiftKey;
        if (code == 13 && shift) {
            if (menuL2Open) {
                e.preventDefault();
                closeLevel2();               
            }           
        }
        else if (code == 13) {
            if (!menuL2Open) {
                e.preventDefault();
                currentLevel2Menu = '#'+$(this).attr('id')+'_menu';
                openLevel2();
            } 
        }        
    });
    

    $('.ActiveMainMenuElement').keydown(function(e) {
        var code = e.which;
        var shift = e.shiftKey;
        if (code == 13 && shift) {
            if (menuL2Open) {
                e.preventDefault();
                closeLevel2();
            }
        }
        else if (code == 13) {
            if (!menuL2Open) {
                e.preventDefault();
                currentLevel2Menu = '#'+$(this).attr('id')+'_menu';
                openLevel2(); 
            }            
        }
    });

    $('.MenuElementWithSubmenu').keydown(function(e) {
        var code = e.which;
        var shift = e.shiftKey;
        if (code == 13 && shift) {
            if (menuL3Open) {
                e.preventDefault();
                $(currentLevel3Menu).css({display: "block", height: slideHeightLevel3, overflow: "hidden"});
                $(currentLevel3Menu).animate({
                    height: 0
                }, 500, function(){$(currentLevel3Menu).css({display:"none"}); menuL3Open = false;});
                $('#MainMenuLevel3Container').slideUp('slow', function() {
                    // Animation complete.
                });
            } 
        }
        else if (code == 13) {
            if (!menuL3Open ){
                e.preventDefault();
                currentLevel3Menu = '#'+$(this).parent().attr("id")+'_menu';
                openLevel3(); 
            } 
        }        
    });

    $(".MainMenuElement").live({
        focusin: function() {
            if (focusSetByHover) {
                focusSetByHover = false;
                return;
            }
            unselectMainMenuElements();
            setActiveMainMenuElement('#'+$(this).attr('id'));
            if (menuL2Open) {
                currentLevel2Menu = '#'+$(this).attr('id')+'_menu';
                showLevel2Content();                
            }          
        }
    });


    $(".ActiveMainMenuElement").live({
        focusin: function() {
            if (focusSetByHover) {
                focusSetByHover = false;
                return;
            }
            unselectMainMenuElements();
            setActiveMainMenuElement('#'+$(this).attr('id'));           
            if (menuL2Open) {
                currentLevel2Menu = '#'+$(this).attr('id')+'_menu';
                showLevel2Content();
            }
        }
    });

    $(".MenuElement").live( {       
        focusin: function() {
            unselectMenuLevel2Elements();
            showMenuButton('#'+$(this).parent().attr("id")+' .MenuElement');
            if (menuL3Open) {
                showLevel3Content();
            }
        }
    });

    $(".MenuElementWithSubmenu").live( {
        focusin: function() { 
            if (focusSetByHover) {
                focusSetByHover = false;
                return; 
            }
            unselectMenuLevel2Elements();
            showMenuButton('#'+$(this).parent().attr("id")+' .MenuElementWithSubmenu');
            if (menuL3Open) {
                $(".MainMenuLevel3").css({ display: "none", height: 0});
                currentLevel3Menu = '#'+$(this).parent().attr("id")+'_menu';
                var currentHeight = slideHeightLevel3;
                setSlideHeightLevel3();
                if (currentHeight != slideHeightLevel3) {
                    $('#MainMenuLevel3Container').animate({height:slideHeightLevel3}, 'slow');
                    $(currentLevel3Menu).css({display: "block", height: currentHeight, overflow: "hidden"});
                    $(currentLevel3Menu).animate({
                        height: slideHeightLevel3
                    }, 500);
                }
                else {
                    $(currentLevel3Menu).css({display: "block", height: slideHeightLevel3});
                }
            }
        }
    });

    // Leaving main menu by tabbing on to header or main content
    $("#MainContent").live({
        focusin: function() { hideMenus();}
    });

    $("#Header").live({
        focusin: function() { hideMenus();}
    });


    // Level 5 menu
    $('#LeftMenu .hasSubmenu').hoverIntent(function() {
       var submenuId = '#'+$(this).siblings('.LevelFiveMenu').attr("id");
       $(this).css({borderBottom: "none"});
       openLevel5(submenuId);
      
    }, function(){});

    $('#LeftMenu').hoverIntent(function(){},
        function(){
            closeLevel5();            
        }, function(){});

    $('.LevelFiveFirstElement').hover(function(){
            var submenuId = '#'+$(this).parent().parent().attr("id");
            $(submenuId+" .LevelFiveTop").css({
                backgroundImage: "url(/TemplatesV2/images/L5_top_selected.png)",
                backgroundPosition: "top",
                backgroundRepeat: "no-repeat"
            })},
            function () {
                var submenuId = '#'+$(this).parent().parent().attr("id");
                $(submenuId+" .LevelFiveTop").css({
                backgroundImage: "url(/TemplatesV2/images/L5_top.png)",
                backgroundPosition: "top",
                backgroundRepeat: "no-repeat"
            })
        });

    $('.LevelFiveFirstElement').focusin(function(){
            var submenuId = '#'+$(this).parent().parent().attr("id");
            $(submenuId+" .LevelFiveTop").css({
                backgroundImage: "url(/TemplatesV2/images/L5_top_selected.png)",
                backgroundPosition: "top",
                backgroundRepeat: "no-repeat"
            })
        });

        $('.LevelFiveFirstElement').focusout(function () {
                var submenuId = '#'+$(this).parent().parent().attr("id");
                $(submenuId+" .LevelFiveTop").css({
                backgroundImage: "url(/TemplatesV2/images/L5_top.png)",
                backgroundPosition: "top",
                backgroundRepeat: "no-repeat"
            })
        });

    $('.LevelFiveLastElement').hover(function(){
            var submenuId = '#'+$(this).parent().parent().attr("id");
            $(submenuId+" .LevelFiveBottom").css({
                backgroundImage: "url(/TemplatesV2/images/L5_bottom_selected.png)",
                backgroundPosition: "top",
                backgroundRepeat: "no-repeat"
            })},
            function () {
                var submenuId = '#'+$(this).parent().parent().attr("id");
                $(".LevelFiveBottom").css({
                    backgroundImage: "url(/TemplatesV2/images/L5_bottom.png)",
                    backgroundPosition: "top",
                    backgroundRepeat: "no-repeat"
                })
        });

    $('.LevelFiveLastElement').focusin(function(){
            $(".LevelFiveBottom").css({
                backgroundImage: "url(/TemplatesV2/images/L5_bottom_selected.png)",
                backgroundPosition: "top",
                backgroundRepeat: "no-repeat"
            })
        });

    $('.LevelFiveLastElement').focusout(function() {
        $(".LevelFiveBottom").css({
                backgroundImage: "url(/TemplatesV2/images/L5_bottom.png)",
                backgroundPosition: "top",
                backgroundRepeat: "no-repeat"
            })
        });

    // Accsesibility: Traversing Left Menu by keys.

    $('#LeftMenu a.hasSubmenu').keydown(function(e) {
        var code = e.which;
        var shift = e.shiftKey;
        if (code == 13 && shift) {
            if (leftMenuOpen) {
                e.preventDefault();
                closeLevel5();                 
            }
        }
        else if (code == 13) {
            if (!leftMenuOpen) {
                e.preventDefault();
                var submenuId = '#'+$(this).siblings('.LevelFiveMenu').attr("id");
                $(this).css({borderBottom: "none"});
                openLevel5(submenuId);                
            }
        }
    });

    // Accessibility: Must be possible to skip navigation. An invisible skip-buttont is added to header 
    $('#Sites').keydown(function(e) {
        if (e.which == 9 && !e.shiftKey) {
            $('#Skip').show();           
        }
    });

    $('#Skip').keydown(function(e) {
        if (e.which == 13) {           
           $('#MainContent a:first').focus();
           $(this).hide(); 
        }
        else if (e.which == 9) {
            $(this).hide();
        }
    });

}

function closeLevel5() {
    $('.LevelFiveMenu').slideUp('slow', function(){
        leftMenuOpen = false;
        $('#LeftMenu .hasSubmenu').css({borderBottom: "1px solid #99cc00"});
    });
}

function openLevel5(menuId) {       
       
       $(menuId).slideDown('slow', function(){leftMenuOpen = true;});
}

// JQuery-plugin downloaded from http://cherne.net/brian/resources/jquery.hoverIntent.html
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:3,interval:100,timeout:600};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

/**
 * jQuery.Preload - Multifunctional preloader
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com
 * Dual licensed under MIT and GPL.
 * Date: 3/25/2009
 * @author Ariel Flesler
 * @version 1.0.8
 */
;(function($){var h=$.preload=function(c,d){if(c.split)c=$(c);d=$.extend({},h.defaults,d);var f=$.map(c,function(a){if(!a)return;if(a.split)return d.base+a+d.ext;var b=a.src||a.href;if(typeof d.placeholder=='string'&&a.src)a.src=d.placeholder;if(b&&d.find)b=b.replace(d.find,d.replace);return b||null}),data={loaded:0,failed:0,next:0,done:0,total:f.length};if(!data.total)return finish();var g=$(Array(d.threshold+1).join('<img/>')).load(handler).error(handler).bind('abort',handler).each(fetch);function handler(e){data.element=this;data.found=e.type=='load';data.image=this.src;data.index=this.index;var a=data.original=c[this.index];data[data.found?'loaded':'failed']++;data.done++;if(d.enforceCache)h.cache.push($('<img/>').attr('src',data.image)[0]);if(d.placeholder&&a.src)a.src=data.found?data.image:d.notFound||a.src;if(d.onComplete)d.onComplete(data);if(data.done<data.total)fetch(0,this);else{if(g&&g.unbind)g.unbind('load').unbind('error').unbind('abort');g=null;finish()}};function fetch(i,a,b){if(a.attachEvent&&data.next&&data.next%h.gap==0&&!b){setTimeout(function(){fetch(i,a,1)},0);return!1}if(data.next==data.total)return!1;a.index=data.next;a.src=f[data.next++];if(d.onRequest){data.index=a.index;data.element=a;data.image=a.src;data.original=c[data.next-1];d.onRequest(data)}};function finish(){if(d.onFinish)d.onFinish(data)}};h.gap=14;h.cache=[];h.defaults={threshold:2,base:'',ext:'',replace:''};$.fn.preload=function(a){h(this,a);return this}})(jQuery);
