// The currently active submenu
var menuCurrent = null;

// Initialize menu event handling
function menuInit() {
    $(".layout-menu-submenu").each(function () {
        var menu = $(this);
        if (menu.find("a").length > 0) {
            var parent = menu.next("a");
            var pos = parent.position();
            pos.left -= 4;
            pos.top += parent.height();
            menu.css(pos);
            parent.mouseover($.proxy(menuShow, this));
            parent.mouseout($.proxy(menuHide, this));
            parent.bind("touchstart", $.proxy(menuTouchShow, this));
            menu.mouseover(menuShow);
            menu.mouseout(menuHide);
        }
    });
    $("body").bind("touchstart", menuTouchHide);
}

// Hides the context element
function menuDisplayNone() {
    $(this).css("display", "none");
}

// Show submenu with fade-in and hide previous submenu
function menuShow() {
    if (menuCurrent !== null && menuCurrent !== this) {
        menuHide.apply(menuCurrent);
    }
    var menu = $(this);
    menu.next("a").addClass("active");
    menu.stop().fadeTo("fast", 1);
    menuCurrent = this;
}

// Hide submenu with fade-out
function menuHide() {
    var menu = $(this);
    menu.siblings("a").removeClass("active");
    menu.stop().fadeTo("fast", 0, menuDisplayNone);
    menuCurrent = null;
}

// Show submenu on first touch, follow link on second touch
function menuTouchShow(event) {
    if (menuCurrent !== this) {
        menuShow.apply(this);
        event.preventDefault();
        event.stopPropagation();
    }
}

// Hide submenu on touch outside menu
function menuTouchHide(event) {
    if (menuCurrent !== null && !$(event.target).is(".layout-menu *")) {
        menuHide.apply(menuCurrent);
    }
}

// Toggle note display
function toggleNote(elem, trigger) {
    elem = (typeof(elem) == 'string') ? $(elem) : $(this);
    if (trigger) {
        var pos = $(trigger).position();
        elem.css({ top: pos.top + 14, left: pos.left - 161 });
        $(".note").addClass("hidden");
    }
    elem.toggleClass("hidden");
}

function targetAction() {
    var href = $(this).find("a:first").attr("href");
    if (href) {
        location.href = href;
    }
}

function targetEnter() {
    $(this).addClass("hover");
    $(this).find("a:first").addClass("hover");
}

function targetExit() {
    $(this).removeClass("hover");
    $(this).find("a:first").removeClass("hover");
}

$(document).ready(function () {
    try {
        document.createEvent("TouchEvent");
        $("body").addClass("touchscreen");
    } catch (e) {
        $("body").addClass("no-touchscreen");
    }
    menuInit();
    $(".note").click(toggleNote);
    $(".target")
        .click(targetAction)
        .hover(targetEnter, targetExit);
});

