$(document).ready(function () {
    $(".topnav-container").each(function (index, elem) {
        $(function () {
            var anchor = $(elem).attr('id').split('_').slice(1).join('_');
            var $phOffset = $("#" + anchor).offset();
            var $containerid = $(elem).attr('id');
            var hidetimer = null;

            $("#" + anchor).mouseenter(function (e) {
                var $phOffset = $("#" + anchor).offset();
                if ($phOffset.left <= ($(window).width() / 2)) {
                    $(elem).css({ left: $phOffset.left + "px", top: ($phOffset.top + 15) + "px" })
                } else {
                    var $adjustedLeft = (($phOffset.left + $("#" + anchor).width()) - $(elem).outerWidth());
                    $(elem).css({ left: $adjustedLeft + "px", top: ($phOffset.top + 15) + "px" })
                }
                var $container = $("#" + $containerid);
                if ($container.hasClass("topnav-container-hidden")) {
                    $container.removeClass("topnav-container-hidden");
                }
                $("#" + anchor).children('img').addClass('disableSwap');
                $("#" + anchor).children('img').attr('src', $("#" + anchor).children('img').attr('src').replace("-0", "-1"));
            });
            $("#" + anchor).mouseleave(function (e) {
                var $container = $("#" + $containerid);
                hidetimer = setTimeout(function () { hideTopNav($container, $("#" + anchor)); }, 10);
            });
            $("#" + anchor).mouseenter(function (e) {
                clearTimeout(hidetimer);
            });
            hideTopNav = function ($container, $anchors) {
                if (!$container.hasClass("topnav-container-hidden")) {
                    $container.addClass("topnav-container-hidden");
                }
                $anchors.children('img').removeClass('disableSwap');
                $anchors.children('img').attr('src', $anchors.children('img').attr('src').replace("-1", "-0"));
            }
            $(elem).mouseenter(function (e) {
                clearTimeout(hidetimer);
            });
            $(elem).mouseleave(function (e) {
                var $container = $("#" + $containerid);
                hidetimer = setTimeout(function () { hideTopNav($container, $("#" + anchor)); }, 10);
            });
        });
    });
});

