var menu_items = new Array();
(function($) {
	$.fn.jinies_toolbar_menu = function(items, options) {
		options = $.extend({
			class_ns: 'hover-item',
			class_hover: 'hover',
			class_active: 'active', // if parent was active, set drop to active
			item_tag: 'a',
			offset_width: 0,
			offset_top: 0,
			offset_left: 0
		}, options);
		var _container, _active, _timer, _hold,
		_compose = function(_key) {
			for ( var i in items[_key] ) {
				if (typeof(items[_key][i]) == 'function') { // action is a function
					_active.append($('<' + options.item_tag + ' >' + i + '</' + options.item_tag + '>').click(items[_key][i]));
				}
				else {
					_active.append('<' + options.item_tag + ' href="' + items[_key][i] + '">' + i + '</' + options.item_tag + '>').hover(_clear_timer(true));
				}
			};
		},
		_menu_hover = function(i) {
			_clear_all();
			var _key = $(i).attr('href');
			if (items[_key]) {
				_active = $('<div></div>');
				_active.css( { "left": ($(i).position().left + options.offset_left) + "px", "top": ($(i).position().top +  $(i).height() + options.offset_top ) + "px" } );
				_active.addClass(options.class_ns);
				_active.css('min-width', ($(i).innerWidth() + options.offset_width) + "px");
				_compose(_key);
				_active.appendTo($('#' + _container));
				_active.hover(function() { _clear_timer(true); }, function() { _clear_all(); });
				if ($(i).parent().hasClass(options.class_active)) {
					_active.addClass(options.class_active);
				}
			}
			$(i).addClass(options.class_hover);
		},
		_menu_out = function() {
			_timer = setTimeout(function() {
				if (_hold == false) {
					_clear_all();
				}
			}, 500);
		},
		_clear_all = function() {
			_clear_timer(false);
			$('#' + _container + ' .' + options.class_hover).removeClass(options.class_hover);
			$('#' + _container + ' .' + options.class_ns).remove();
		},
		_clear_timer = function(on_hold) {
			_hold = on_hold;
			if (_timer) {
				clearTimeout(_timer);
				_timer = null;
			}
		};
		this.each(function() {
			if (!this.id) {
				this.id = options.class_ns + '-container';
			}
			_container = this.id;
			$(this).find('a.drop').each(function(x, i) {
				$(i).hover(function() { _menu_hover(i); }, function() { _menu_out(); });
			});
		});
		return items;
	};
})(jQuery);
