(function($){
 $.fn.ddmenu = function(options) 
 {
	var defaults = 
	{
	   fadeIn: 200,
	   fadeOut: 200,
	   rolloverTime: -1,
	   reference: '#cgmain',
	   topOffset: 0
	};
	var options = $.extend(defaults, options);
 
    return this.each(function() 
	{
		obj = $(this);
		var objPosition = obj.position();
		var position = $(options.reference).position();
		var offset = $(options.reference).offset();
		
		var oldDiv = null;
		
		$('#' + obj.attr('id') + '> div > ul > li').find('a').each(
			function(idx, elt) 
			{
				//alert($(elt).attr('id'));
				var id = $(elt).attr('id');
				var divId = '#' + id + 'dd';
				var hide = false;
				var hide2 = false;
				var hoverDiv = false;
				$(elt).hover(
					function()
					{
					    var currentDiv = $(divId);
					    if (oldDiv != null && oldDiv != currentDiv)
					    {
					        oldDiv.hide();
					    }
					    oldDiv = currentDiv;
						var rolloverTime = options.rolloverTime;
						if (hide)
						{
							//clearTimeout(hide);
							rolloverTime = -1; // avoid waiting when switching between menus
						}
						currentDiv.css('left', position.left + 150);
						currentDiv.css('top', offset.top + options.topOffset);
						//$(divId).css('background-position', (obj.left / 2) + 'px top');
						//if (rolloverTime != -1)
						//	hide2 = setTimeout(function() {$(divId).slideDown(options.fadeIn)}, options.rolloverTime);
						//else
							currentDiv.show();
						$(this).addClass("active");
					},
					function() 
					{
						if (hide2)
						{
							//clearTimeout(hide2);
							if (! hoverDiv)
								$(divId).hide();
						}
						else
						{
						    //if (options.fadeOut == -1)
						    //{
						        $(divId).hide();
						    //}
						    //else
						    //{
							    // Fades out the DIV and removes the 'active' class from the main nav menu item
							   // hide = setTimeout(function() {$(divId).slideUp(options.fadeOut);});
							//}
						}
						oldDiv = null;
						//$(divId).stop().fadeIn();
						$(this).removeClass("active");
					}
				);
				
				 $(divId).hover(
					function()
					{
						hoverDiv = true;
						//if (hide)
						//	clearTimeout(hide);
						$(divId).show();
						$(id).addClass("active");
					}, 
					function() 
					{
						hoverDiv = false;
						if (hide)
						{
							clearTimeout(hide);
							//$(divId).hide();
						}
						if (hide2)
							clearTimeout(hide2);
						//hide = setTimeout(function() {$(divId).slideUp(options.fadeOut);});
						$(divId).hide();
						//$(divId).stop().fadeIn(options.fadeIn);
						$(id).removeClass("active");
					}
				);
			}
		);
    });
 };
})(jQuery);

