var yndenz = yndenz || function () {
    return {};
};
yndenz.modules = yndenz.modules || function () {
    return {};
};

yndenz.modules.navigation = yndenz.modules.navigation || function () {
    return {};
};

yndenz.modules.navigation.dropdown = function (target, options) {
    this.target = target;
    this.options = options;
    this.timeout = null;
    this.open = this.target.hasClass('open');

    this.watch('open', function (prop, oldVal, val) {
        if (oldVal !== val) {
            if (val) {
                this.target.addClass('open');
            } else {
                this.target.removeClass('open');
            }
        }

        return val;
    });

    this.target.parent().find('> .dropdown-toggle, > .submenu-toggle').on('click', $.proxy(this.toggle, this));
    this.target.parent().on('mouseenter', $.proxy(this.mouseenter, this));
    this.target.parent().on('mouseleave', $.proxy(this.mouseleave, this));
};

yndenz.modules.navigation.dropdown.prototype.toggle = function (e) {
    e.preventDefault();
    e.stopPropagation();
    if (this.timeout) {
        clearTimeout(this.timeout);
    }
    this.open = !this.open;
};

yndenz.modules.navigation.dropdown.prototype.setOpened = function () {
    this.open = true;
};

yndenz.modules.navigation.dropdown.prototype.setClosed = function () {
    this.open = false;
};

yndenz.modules.navigation.dropdown.prototype.mouseenter = function () {
    if (this.options.openOnHover && $(window).width() >= window.gridFloatBreakpoint) {
        this.timeout = setTimeout($.proxy(this.setOpened, this), 10);
    }
};

yndenz.modules.navigation.dropdown.prototype.mouseleave = function () {
    if (this.options.openOnHover && $(window).width() >= window.gridFloatBreakpoint) {
        this.timeout = setTimeout($.proxy(this.setClosed, this), 10);
    }
};

yndenz.modules.navigation.dropdown.defaults = {
    openOnHover: false
};

(function () {
    $.fn.extend({
        dropdown: function (options) {
            options = $.extend({}, yndenz.modules.navigation.dropdown.defaults, options);

            this.each(function () {
                new yndenz.modules.navigation.dropdown($(this), $.extend({}, options, $(this).data()));
            });

            return this;
        }
    });
})(jQuery);

jQuery(function () {
    $('.dropdown-submenu').dropdown({openOnHover: false});
    $('.dropdown-menu').dropdown({openOnHover: true});
});