$(document).ready(function() {

	var mainMenuOffsetLeft = 13;
	var mainMenuOffsetTop = 9;
	var nrMainMenus = 0;
	var mainMenuTimeout;
	
	var mainMenuPrepend = '<div class="menu-overlay main-menu-overlay"><div class="menu-top"><div class="topleft"></div><div class="toptitle"></div>'
				+ '<div class="topcenter"></div><div class="top"></div><div class="topright"></div></div>'
				+ '<div class="menu-middle"><div class="left"></div><div class="center"><div class="base-menu"><ul class="submenu">';
	var mainMenuAppend  = '</ul></div><div class="sub-menu"><ul class="subsubmenu"></ul></div></div><div class="right"></div></div>'
				+ '<div class="menu-bottom"><div class="bottomleft"></div><div class="bottom"></div><div class="bottomright"></div></div></div>';
    
	$('#nav-main a[rel=popover-menu] em').each(function() {
		var menuID = '#popover-main-menu-generated-' + (++nrMainMenus);
		$(this).parent().parent().attr('rel', menuID);
        $(this).data('visible', false);
        $(this).data('initialized', false);
		if ($(this).parent().parent().parent().find('ul').length) {
			$('#content_conteiner').append(mainMenuPrepend + $(this).parent().parent().parent().find('ul:first').html() + mainMenuAppend);
			$('#content_conteiner .main-menu-overlay:last').attr('id', menuID.substring(1));
			if ($(this).parent().parent().parent().find('ul').length > 1) {
				menu = $('#content_conteiner .main-menu-overlay:last');
				menu.find('.subsubmenu').html($(this).parent().parent().parent().find('ul:last').html());
				menu.find('.topright').addClass('topright-grey').before('<div class="topcenter-grey"></div><div class="top-grey"></div>');
				menu.find('.bottomright').addClass('bottomright-grey').before('<div class="bottomcenter-grey"></div><div class="bottom-grey"></div>');
				menu.find('.right').addClass('right-grey');
				menu.find('.base-menu').css({'padding-right':'16px', 'margin-right':'0'});
			}
			else {
				$('#content_conteiner .main-menu-overlay:last .sub-menu').remove();
			}
		//start
			menu = $($(this).parent().parent().attr('rel'));
			position = $(this).parent().parent().offset();
			
			var titleWidth = $(this).parent().parent().outerWidth();
			menu.find('.toptitle').css('width', titleWidth);
			var topHeight = 41;//$(this).outerHeight();
			menu.find('.menu-top div').css('height', topHeight);
			$(this).data('contentHeight', menu.find('.base-menu').outerHeight());
			$(this).data('middleHeight', menu.find('.center').outerHeight());
			menu.find('.right').css('height', $(this).data('middleHeight'));
			menu.find('.left').css('height', $(this).data('middleHeight'));
			//rechts menu
			if (menu.find('.sub-menu').length) {
				var totalWidth = parseInt(menu.find('.menu-middle .center .base-menu').outerWidth()) + 26 + 1;
				if (totalWidth < titleWidth + 38) {
					totalWidth = titleWidth + 39;
					menu.find('.base-menu').css('width', totalWidth-53);
				}
				var restWidth = parseInt(menu.find('.menu-middle .center').outerWidth()) + 16 - totalWidth;
				$(this).data('baseWidth', parseInt(menu.find('.menu-middle .center').outerWidth()) + 26);
				menu.css('width', $(this).data('baseWidth') + 1);
				var topWidth = 0;
				menu.find('.menu-top div').each(function(){topWidth += $(this).outerWidth()});
				$(this).data('topWidth', totalWidth - topWidth + 10);
				menu.find('.top').css('width', $(this).data('topWidth'));
				menu.find('.top-grey').css('width', restWidth);
				var bottomWidth = 0;
				menu.find('.menu-bottom div').each(function(){bottomWidth += $(this).outerWidth()});
				$(this).data('bottomWidth', totalWidth - bottomWidth + 10);
				menu.find('.bottom').css('width', $(this).data('bottomWidth'));
				menu.find('.bottom-grey').css('width', restWidth);
				menu.find('.sub-menu').css('height', menu.find('.base-menu').height());
				
			}
			else {
				var totalWidth = parseInt(menu.find('.menu-middle .center').outerWidth()) + 26;
				if (totalWidth < titleWidth + 38) {
					totalWidth = titleWidth + 38;
					menu.find('.base-menu').css('width', totalWidth-46);
				}
				$(this).data('baseWidth', totalWidth);
				menu.css('width', totalWidth+1);
				var topWidth = 0;
				menu.find('.menu-top div').each(function(){topWidth += $(this).outerWidth()});
				$(this).data('topWidth', totalWidth - topWidth);
				menu.find('.top').css('width', $(this).data('topWidth'));
				var bottomWidth = 0;
				menu.find('.menu-bottom div').each(function(){bottomWidth += $(this).outerWidth()});
				$(this).data('bottomWidth', totalWidth - bottomWidth);
				menu.find('.bottom').css('width', $(this).data('bottomWidth'));
			}
            menu.animate({opacity: 0}, 0);
        //end
		}
		else {
            $(this).data('noContent', true);
		}
	})
	.hover(function(evt) {
	
		$(this).data('hovering', true);
	
        evt.stopPropagation();
        if ($(this).data('noContent')) {
        	$(this).parent().parent().parent().addClass('noContentHover');
        	return true;
        }
        if ($(this).data('visible')) {
        	return false;
        }
    
        var menu = $($(this).parent().parent().attr('rel'));
		var position = $(this).parent().parent().offset();
		
	  //position submenu
	  
		menu.css('top', Math.round(position.top - mainMenuOffsetTop));
		menu.css('left', Math.round(position.left - mainMenuOffsetLeft));
		
	  //show requested menu
		
        hideAllMenus();
		link = $(this).parent().parent().parent();
		that = this;
		menu.css('overflow', 'visible')
			.css('height', 'auto')
			.stop(true, false)
			.animate({opacity: 0}, 150, function(){
				$(this).show();
				link.addClass('current');
				$(that).data('visible', true);
			})
			.animate({opacity: 1}, 200);
		//menu.find('.center').style('height', '100px');
//		if($.browser.msie) menu.find('.toptitle').html($(this).html());

		return false;
        
	}, function(){
        if ($(this).data('noContent')) {
        	$(this).parent().parent().parent().removeClass('noContentHover');
        	return true;
        }
		if (!$(this).data('visible') && !$(this).data('a-hover')) {
			menu = $($(this).parent().parent().attr('rel'));
			menu.stop(true, false);
			hideMenu($(this));
		}
		$(this).data('a-hover', false);
		$(this).data('hovering', false);
//	})
//    .click(function(){
//        return ($(this).data('noContent') ? true : false);
    });

    $('.main-menu-overlay').hover(function(evt){
    	//nonono
    }, function(evt){
    	menuItem = $('a[rel=#'+$(this).attr('id')+'] em');
    	if (menuItem.data('hovering')) return;
        if (menuItem.data('visible')) {
            hideMenu($('a[rel=#'+$(this).attr('id')+'] em'));
        }
    })
	
	function hideMenu(menuItem) {
		menuItem.data('visible', false);
		setTimeout(function(){
			if (!menuItem.data('hovering')) {
				menu = $(menuItem.parent().parent().attr('rel'));
      	  		menu.stop(true, false).animate({opacity: 0}, 200, function(){
      	    		$(this).hide().css('width', menuItem.data('baseWidth') + 1);
      			}); 
      			menuItem.parent().parent().parent().removeClass('current');
      		}
        }, 1);
	}
    
    function hideAllMenus() {
        $('ul#nav-main > li > a > span > em').each(function(){
            if ($(this).data('visible')) {
                hideMenu($(this));
            }
        })
    }
	
});


/**
 * Concatenates the values of a variable into an easily readable string
 * by Matt Hackett [scriptnode.com]
 * @param {Object} x The variable to debug
 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
 * @param {String} sep The separator to use between [default: a single space ' ']
 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use
 */
function print_r(x, max, sep, l) {

	l = l || 0;
	max = max || 10;
	sep = sep || ' ';

	if (l > max) {
		return "[WARNING: Too much recursion]\n";
	}

	var
		i,
		r = '',
		t = typeof x,
		tab = '';

	if (x === null) {
		r += "(null)\n";
	} else if (t == 'object') {

		l++;

		for (i = 0; i < l; i++) {
			tab += sep;
		}

		if (x && x.length) {
			t = 'array';
		}

		r += '(' + t + ") :\n";

		for (i in x) {
			try {
				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
			} catch(e) {
				return "[ERROR: " + e + "]\n";
			}
		}

	} else {

		if (t == 'string') {
			if (x == '') {
				x = '(empty)';
			}
		}

		r += '(' + t + ') ' + x + "\n";

	}

	return r;

};
var_dump = print_r;

