(function ($) {
	
    $.menu = function (el, options) {
        var self = this,
			node = $(el),
			tabs = $('li', node),
			sub = $('#submenu'),
			contents = $('.submenu-inner', sub),
			ie = $.browser.msie ? 1 : 0,
			visible = false;

		node.data('menu', this);
		
		/**
		 *	Initializing
		 */
        this.init = function () {
            this.options = $.extend({}, $.menu.defaultOptions, options);
			
			//if (!ie) sub.css({opacity: 0});
			
			tabs.click(this._enter);
			
			tabs.hover(this._over, this._out);
			
			sub.click(function (e) {
				e.stopPropagation();
			});
			
			$('body').click(this._leave);
			
			$('.inner > div', sub)
				.mouseenter(this._enterInner)
				.mouseleave(this._leaveInner);
        };
		
		this._enterInner = function () {
			$(this).parent().addClass('hover');
		};
		
		this._leaveInner = function () {
			$(this).parent().removeClass('hover');
		};
		
		this._over = function () {
			$(this).addClass('mousehover');
			Cufon(target.get(0));
			return false;
		};
		
		this._out = function () {
			$(this).removeClass('mousehover');
			Cufon(target.get(0));
			return false;
		};
		
		this._enter = function () {
			var target = $(this),
				rel = $('a', target).attr('rel');
			
			if (!rel) return;
			
			if (target.hasClass('hover')) {
				self._leave();
				return false;
			} else if (visible) {
				self._leave();
			}
			
			target.addClass('hover');
			Cufon(target.get(0));
			
			node.addClass('subbed');
			sub.show();
			contents.hide().css('visibility', 'hidden');
			$('#' + rel).show().css('visibility', 'visible');
			
			visible = true;
			return false;
		};
		
		this._leave = function (e) {
			if (!visible) return;
			visible = false;
			
			var tab = tabs.filter('.hover');
			tab.removeClass('hover');
			Cufon(tab.get(0));
			
			node.removeClass('subbed');
			sub.hide();
		};

        this.init();
    };

    $.menu.defaultOptions = {
		active: 0
    };

    $.fn.menu = function (options) {
        return this.each(function () {
            (new $.menu(this, options));
        });
    };

})(jQuery);
