$(document).ready(function() {
    $('.level2').click(function () {
        $(this).hide();
    });
    $('ul.level1 > li:even').css('fontWeight', 'bold');
    $('#header_mainmenu ul.level2 > li').each(function () {
        if (1 == $(this).children().length && "Neue Produkte" != $(this).parent().parent().find('a').html()) {
            $(this).remove();
        }
    });
    $('ul.level2 > li:last-child').css('border', '0');
    $('ul.level3 > li:first-child a').css('fontStyle', 'italic');
	function mouseIn() {
	    var sm = $(this).find(".level2");
		sm.stop().fadeTo('fast', 1).show();
		
		var a = $(this).find('a:first-child');
		var c = a.css('backgroundColor');
		a.addClass('hover');
		sm.css('backgroundColor', c);
		
		//Calculate width of all ul's
		(function($) {
			jQuery.fn.calcSubWidth = function(nr) {
				rowWidth = 0;
				//Calculate row
				$(this).find("ul.level" + nr).each(function() {
					rowWidth += $(this).width();
				});
			};
		})(jQuery);
		if ("Neue Produkte" != sm.parent().find('a').html()) {
		    $(this).calcSubWidth(3);
		} else {
		    rowWidth = 160;
		}
		//Set Width
		sm.css({
            'width' : rowWidth + 10,
            'zIndex': 9000
		});
		// check if the submenu is bigger than the menu to realign
		var sWidth    = parseInt($(this).css('width'), 10);
		var mWidth    = parseInt($(this).parent().css('width'), 10);
		var ePosition = $(this).position().left;
		var smWidth   = parseInt(sm.css('width'), 10);
	    if ((smWidth + ePosition + 0) > mWidth) {
	        sm.css('left', -1 * (smWidth - (mWidth - ePosition) + 0) + 'px');
	    }
        $(this).css({
            'zIndex' : 8000
        });
	}
    function mouseOut()
    {
        var sm = $(this).find(".level2");
        sm.stop().fadeTo('fast', 0, function() {
	        $(this).hide();
        });
        var a = $(this).find('a');
		a.removeClass('hover');
        $(this).css({
    	   'zIndex' : 0
        });
	}
	var config = {
		 sensitivity: 2,      // number = sensitivity threshold (must be 1 or higher)
		 interval: 100,       // number = milliseconds for onMouseOver polling interval
		 over: mouseIn, // function = onMouseOver callback (REQUIRED)
		 timeout: 500,        // number = milliseconds delay before onMouseOut
		 out: mouseOut    // function = onMouseOut callback (REQUIRED)
	};
	$("ul.level1 li .level2").css({'opacity':'0'});
	$("ul.level1 li").hoverIntent(config);
});
