﻿$(document).ready(function() {

    var timeout = 500;
    var closeTimer = 0;

    // Set Mega Menu Close Time
    function setMegaMenuClose(megaMenuItem) {
        closeTimer = window.setTimeout(function() { megaMenuClose(megaMenuItem); }, timeout);
    }

    // Cancel Mega Menu Close Time
    function cancelMegaMenuClose() {
        if (closeTimer) {
            window.clearTimeout(closeTimer);
            closeTimer = null;
        }
    }

    // Mega Menu Close
    function megaMenuClose(megaMenuItem) {
        megaMenuItem.find("img").attr("src", megaMenuItem.find("img").attr("src").replace("_On", "_Off"));
        $("#" + megaMenuItem.find("a").attr("rel")).hide();
    }

    $(".megaMenuItem").each(function(index) {
        var megaMenuItem = $(this);

        // Hover Events For Mega Menu Item
        megaMenuItem.find("img").hover(
            function() {
                // Reset
                $(".megaMenuItem").each(function(index) {
                    megaMenuClose($(this));
                });

                cancelMegaMenuClose();
                $(this).attr("src", $(this).attr("src").replace("_Off", "_On"));
                $("#" + megaMenuItem.find("a").attr("rel")).show();
            },
            function() {
                setMegaMenuClose(megaMenuItem);
            }
        );

        // Hover Events For Mega Menu Content
        $("#" + megaMenuItem.find("a").attr("rel")).hover(
            function() {
                cancelMegaMenuClose();
                megaMenuItem.find("img").attr("src", megaMenuItem.find("img").attr("src").replace("_Off", "_On"));
                $("#" + $(this).attr("rel")).show();
            },
            function() {
                setMegaMenuClose(megaMenuItem);
            }
        );



    });

});

