$(window).load(function () {

    // posizione il margine sinistro del sottomenu
    var leftPos = $("#mainNav").position();
    $("#secondNav ul").each(function (i) {
        var identity = $(this).attr("class");
        var position = $("#mainNav li[id=" + identity + "]").position();
        $(this).css("left", leftPos.left + position.left);
    });

    
    var timer;
    var timerSub;
    var timerSubSub;

    // effetto a scomparsa del sottomenu
    var menuAttivo = $("#mainNav > li.active").attr("id");
    $("#secondNav ul[class=" + menuAttivo + "]").css("display", "block");

    $("#mainNav > li[class != 'active']").mouseleave(function () {
        var identity = $(this).attr("id");
        var secondNav = $("#secondNav ul[class=" + identity + "]");
        timer = setTimeout(function () {
            $(secondNav).mouseover(function () {
                clearTimeout(timer);
            });

            secondNav.hide(0);
        }, 50);
    });
    
    

    $("#mainNav > li[class != 'active']").mouseenter(function () {
        /*clearTimeout(timer);*/
        $("#secondNav ul[class=" + menuAttivo + "]").hide(0);
        var identity = $(this).attr("id");
        $("#secondNav ul[class=" + identity + "]").show(0);
    });


    $("#mainNav").mouseleave(function () {
        timerSub = setTimeout(function () {
            $("#secondNav ul").mouseover(function () {
                clearTimeout(timerSub);
            });
            $("#secondNav ul[class=" + menuAttivo + "]").show(0);
        }, 50);
        
    });

    $("#secondNav ul").mouseleave(function () {
        var identity = $(this).attr("class");
        timerSubSub = setTimeout(function () {
            $("#mainNav li[id=" + identity + "]").mouseover(function () {
                clearTimeout(timerSubSub);
            });
            $("#mainNav li[id!=" + identity + "]").mouseover(function () {
                $("#secondNav ul[class=" + identity + "]").hide(0);
                clearTimeout(timerSubSub);
            });
            $("#secondNav ul[class=" + identity + "]").hide(0);
            $("#secondNav ul[class=" + menuAttivo + "]").show(0);
        }, 50); 
    });



}); 
