(function ($) {
    var navis = new Array();
    var current = null;

    $.extend($.fn, {
        navi: function () {
            var _this = this;

            this.addClass('navi');

            var items = this.children('a').addClass('navi-item');
            var subItems = this.children('div').addClass('navi-sub');

            $.each(items, function (i, o) {
                navis[i] = new Object();
                navis[i].main = $(o);
            });
            $.each(subItems, function (i, o) {
                navis[i].sub = $(o);
            });

            this.children('div').each(function (i, o) {
                $(this).children('a').addClass('navi-sub-item');
            });

            $.each(navis, function (i, o) {
                $(o.main).hover(function () {
                    if (current) {
                        _this.hiddenSub();
                    }
                    if (_this.timer) {
                        _this.cancelTimer();
                    }
                    _this.showSub(o);
                }, function () {
                    current = o;
                    _this.createTimer();
                });
                $(o.sub).hover(function () {
                    _this.cancelTimer();
                }, function () {
                    current = o;
                    _this.createTimer();
                });
            });
        },
        timer: null,
        createTimer: function () {
            this.timer = window.setTimeout(this.hiddenSub, 300);
        },
        cancelTimer: function () {
            if (this.timer) {
                window.clearTimeout(this.timer);
                this.timer = null;
            }
        },
        showSub: function (o) {
            if (o.sub.children('a').size() > 0) {
                o.main.addClass('navi-item-selected');
            }
            o.sub.show();
            var left = (o.main.position().left + o.main.width() * 0.75) - o.sub.width() / 2;
            if ($.browser.version == "6.0") {
                left -= 400;
            }
            var bodywidth = $('body').width();
            if ((bodywidth - left - o.sub.width()) < 0) {
                o.sub.css('right', 0);
            }
            else {
                o.sub.css('left', left);
            }
        },
        hiddenSub: function () {
            current.main.removeClass('navi-item-selected');
            current.sub.hide();
        }
    });
})(jQuery);
