$(document).ready(function () {

    //Wrap alle submenu's
    $("#menu ul li > ul:not(ul + ul)").each(function () {
        $(this).nextUntil(':not(ul)').andSelf().wrapAll('<div/>');
    });

    //Preview invoegen
    $("#menu > ul > li > a").each(function () {

        //Producten
        if ($(this).text() == "Producten") {

            //preview
            $(this).siblings("div").prepend("<span><img class='menuPreview' src='/Content/Images/empty.gif'/></span>");

            //mouseactions
            $(this).siblings("div").find("a").mouseover(function () {
                //console.debug($(this).text());
                var previewClass = this.href.substring(this.href.lastIndexOf('/') + 1);
                $(".menuPreview").addClass(previewClass);
            });
            $(this).siblings("div").find("a").mouseout(function () {
                var previewClass = this.href.substring(this.href.lastIndexOf('/') + 1);
                $(".menuPreview").removeClass(previewClass);
            });
        }
    });

    //mouseover main
    $("#menu > ul > li").mouseover(function () {

        var width = 0;
        $(this).find("ul").each(function () {
            width += $(this).outerWidth(true);
        });
        $(this).find("span").each(function () {
            width += $(this).outerWidth(true);
        });
        $(this).find("div").css('width', width + 0);

        var mainMenuWidth = $(this).width();
        var subMenuWidth = $(this).find("div").width();
        subMenuWidth = subMenuWidth + 40; //40 = 2x20 padding (#menu > ul > li > div)
        var offset = parseInt((subMenuWidth - mainMenuWidth) / 2);
        $(this).find("div").css('left', -offset);
    });

    if (!pageUrl) {
        pageUrl = "Home";
    }
    $("#menu > ul > li").has("a[href*=" + pageUrl + "]").addClass('selected');

});

