﻿Agility.RegisterNamespace("CleanEating.Controls");

(function () {

    var MainMenu = CleanEating.Controls.MainMenu = function (containerID) {
        this._containerID = containerID;
    };

    MainMenu.prototype.init = function () {
        var menu = this,
            container = $("#" + this._containerID),
            topLevelLinks = $(".TopLevelLink", container),
            childMenus = $(".SecondLevelContainer", container),
            secondLevelLinks = $(".SecondLevelLink", container),
            closeTimeout;

        topLevelLinks.hoverIntent(function () {
            var offset = $(this).offset(),
                images = container.find(".MenuImage"),
                image = $(this).find("img");

            images.each(function () {
                $(this).attr("src", $(this).attr("normalSrc"));
            });
            image.attr("src", image.attr("hoverSrc"));
            
            clearTimeout(closeTimeout);
            childMenus.hide();

            $(this).parent().find(".SecondLevelContainer").css({
                top: offset.top + 40,
                left: offset.left
            }).show();
        }, function () {
            var topLevelLink = $(this),
                image = $(this).find("img");

            closeTimeout = setTimeout(function () {
                image.attr("src", image.attr("normalSrc"));
                topLevelLink.parent().find(".SecondLevelContainer").hide();
            }, 500);
        });

        childMenus.hoverIntent(function () {
            clearTimeout(closeTimeout);
        }, function () {
            var childMenu = $(this),
                image = childMenu.parent().find("img");
            closeTimeout = setTimeout(function () {
                image.attr("src", image.attr("normalSrc"));
                childMenu.hide();
            }, 500);
        });

        secondLevelLinks.hoverIntent(function () {
            $(this).addClass("Hover");
        }, function () {
            $(this).removeClass("Hover");
        });
    };

}());
