﻿$(document).ready(function() {
    $('#nav').InitNavigation();
});

/* INIT NAVIGATION
----------------------------------------------------*/
(function ($) {
    $.fn.InitNavigation = function () {
        var nav = $(this);
        var navItem = nav.find('li');
        var closeTimeOut = null;
        nav.find('a').css('z-index', '999');
        navItem.bind('mouseenter', function (navEvent) {

            var thisMenuItemId = $(this).find('a').attr('rel');
            var currMenuItemId = $('#nav-dropmenu').attr('class');

            $("#nav-dropmenu").css('z-index', '899');

            if (thisMenuItemId != currMenuItemId) {
                $('#nav-dropmenu').fadeOut('fast').delay(500).remove();
                nav.find('li').removeClass('active');
                $(this).toggleClass('active');
                var maxOffset = 950;
                var pos = $(this).position();
                var leftOffset = pos.left;
                var menuId = $(this).find('a').attr('rel');
                var currNavItem = $('#menufolds .' + menuId).clone();
                var dropMenu = $('<div id="nav-dropmenu" class="' + menuId + '"><div></div></div>');
                dropMenu.hide();
                dropMenu.css('left', leftOffset);
                dropMenu.css('z-index', '899');
                dropMenu.find('div').append(currNavItem);
                $('form').append(dropMenu);
                var menuWidth = (dropMenu.width());
                var currOffset = (0 + leftOffset + menuWidth);
                if (currOffset > maxOffset) {
                    var diff = (currOffset - maxOffset);
                    dropMenu.css('width', menuWidth - diff)
                }
                dropMenu.show();

                $.data(dropMenu, 'currLi', $(this));

                // Reorder
                nav.find('a').css('z-index', '900');

                $(this).find('a').bind('mouseenter', function () {
                    clearTimeout(closeTimeOut);
                });

                var closeMenu = function () {
                    dropMenu.fadeOut('fast').delay(500).remove();
                    $.data(dropMenu, 'currLi').removeClass('active');
                }

                dropMenu.bind('mouseleave', function (e) {
                    clearTimeout(closeTimeOut);
                    closeTimeOut = setTimeout(closeMenu, 100);
                });

                dropMenu.bind('mouseenter', function (e) {
                    clearTimeout(closeTimeOut);
                });
            }
            return false;
        });

        $(document).bind('click', function () {
            $('#nav-dropmenu').fadeOut('fast').delay(500).remove();
            $('#nav').find('li').removeClass('active');
        });
    };
})(jQuery);

