// This initializes the menu
$(function() {
	$('ul.mMenu').mMenu();
	$('ul.mMenu, ul.mMenu > li > ul').each(function() {$('> li:not(:last)', this).css('border-bottom','1px solid #777');});
	$('.accessible').closest('li').css({cursor: 'default'});
	$('.accessible').css({cursor: 'default'});
	$('.mMenuResizeWidth').each(function() {
		var ul = $(this).clone();
		ul.css({'background-color':'red'});
		$('body').append(ul);
		ul.css({'position':'absolute'})
			.show();
		var sx = ul.width();
		if (sx < 150)
		{
			sx = 150;
		}
		$('>li', this).width(sx);
		ul.remove();
		});
});

(function($){
	function addEvents(ul) {
		var settings = $.data( $(ul).parents().andSelf().filter('ul.mMenu')[0], 'mMenuSettings' );
		$('> li', ul)
			.unbind().bind('mouseenter.mMenu mouseleave.mMenu', function(evt) { // LW - unbind
					if (evt.type == 'mouseenter')
					{
						$(this).not('.donthover').addClass('mMenuHover');
						$(this).parents('li').not('.donthover').addClass('mMenuHover');
					} else {
						$(this).removeClass('mMenuHover');
						}
				var input = $('input:visible', this);
				if (input.length > 0)
				{
					if (!$(this).parent().hasClass('mMenu'))
					{
						if (evt.type=='mouseenter')
						{
							input[0].focus();
						} else {
							input[0].blur();
						}
					}
				}
				var ul = $('> ul', this);
				if ( ul.length == 1 ) {
					clearTimeout( this.$mMtimer );
					var enter = ( evt.type == 'mouseenter' );
					var fn = ( enter ? showMenu : hideMenu );
					fn( ul[0], settings.onAnimate );
				}
			})
			.bind('click.mMenu', function(evt, secondpass) {
				//console.log("mMenu.js -> click.mMenu");
				// The user clicked the li and we need to trigger a click for the a
				if(!$(evt.target).is('a') ) {
					var closest_li = $(evt.target).closest('li');
					var link = $('> a', closest_li).not('.accessible');
					if ( link.length > 0 ) {
						var a = link[0];
						if ( !a.onclick ) {
							window.open( a.href, a.target || '_self' );
						} else {
							evt.stopPropagation();
							$(a).trigger('click', true);
						}
					}
				}
				if ( settings.disableLinks || 
					( !settings.disableLinks && !$(this).parent().hasClass('mMenu') ) ) {

					if (!$(this).hasClass('accessible'))
					{
						$(this).parent().mMenuHide();
					}
//					evt.stopPropagation();
				}
			})
			/*
			.find('> a')
				.filter('.accessible')
					.bind('click.mMenu', function(evt) {
						evt.preventDefault();
					});
					*/
	}

	function showMenu(ul, animate ) {
		var ul = $(ul);
		var size_div  = $('> li > div:first', ul);
		if(size_div.width() > 1)
		{
			// these lines outcommented due to bug, where the calendar in the menu would make the parent ul render with 0px height
			// as far as I can see, the outerHeight is not used for anything, and the height it automatically sets looks alright
			// the Width is changed, so it adds 10px, since the padding is 5px on each side (and it would otherwise be too narrow)
			// LW 22-03-2011
//			ul.width(size_div.outerWidth());
//			ul.height(size_div.outerHeight());
			ul.width(size_div.outerWidth()+10);
		}
		// prevent addEvents to run multiple times on the same element (ul)
		if ( !ul.hasClass('mM_events') ) {
			ul.addClass('mM_events');
			addEvents(ul);
		}
		ul.show();
		ul.position({
			of: ul.parent(),
			my: "left top",
			at: "right top",
			offset: "-5 1",
			collision: "fit fit"
		});
		return;
	}


	function hideMenu(ul, animate) {
		var ul = $(ul);
		ul.hide()
		return;
	}
	
	// Public methods
	$.fn.mMenu = function(settings) {
		// Future settings: activateDelay
		if (window.madlog_mobile) {
			var factor = 10; } else {
			var factor = 1; }
		var settings = $.extend({
			// Time in ms before menu hides
			hideDelay: 		1000 * factor,
			// Should items that contain submenus not 
			// respond to clicks
			disableLinks:	true
			// This callback allows for you to animate menus
			//onAnimate:	null
			}, settings);
		if ( !$.isFunction( settings.onAnimate ) ) {
			settings.onAnimate = undefined;
		}
		return this.filter('ul.mMenu').each(function() {
			$.data(	this, 
					'mMenuSettings', settings); 
			addEvents(this);
			if ($(this).hasClass('mMenu')){
				$(this).bind('popup_menu.mM_main', function(evt, e) {
						$(".popup").remove();
						$('.mTooltip').trigger('mouseleave');
						$('ul.mMenu > li > ul').each(function() {$(this).removeData('offset');$(this).removeClass('mM_events');});
						//$('ul.mMenu > li > ul').each(function() {$(this).removeClass('mM_events');});
						$(this)
							.css({'left' : '', 'top' : ''})
							.show()
							.position({of: e, my: "left top", offset: "3 3"});
					e.stopPropagation();
//					e.preventDefault();
					});
			}
			$(this).bind('mouseenter.mM_mainul mouseleave.mM_mainul popup_menu.mM_mainul', function(evt) {
					var menu = this;
					clearTimeout( this.$mMtimer );
					if (evt.type == 'mouseleave' ||evt.type == 'popup_menu')
					{
						var delay;
						if (evt.type == 'mouseleave') {
							delay = settings.hideDelay; }
						if (evt.type == 'popup_menu') {
							delay = settings.hideDelay; }
						this.$mMtimer = setTimeout(function() {
							$(menu)
								.mMenuHide()
								.trigger('hide_menu');
						}, delay );
					}
				});
		});
	};
	
	$.fn.mMenuHide = function() {
		return this.filter('ul').each(function(){ 
			hideMenu( this );
		});
	};

	$.fn.cutnpaste = function(obj, to) {
		if (!obj.data('sx'))
		{
			$('body').append(obj);
			obj.css({'position' : 'absolute'});
			obj.show();
			obj.data('sx', obj.outerWidth() +1 );
			obj.data('sy', obj.outerHeight());
			obj.css({'position' : ''});
		}
		to.css({'padding-left': '0px'});
		to.css({'padding-top': '0px'});
		to.css({'line-height': 'normal'});
		to.width(obj.data('sx'));
		to.height(obj.data('sy'));
		to.append(obj);
		return this;
	}

	// Private methods and logic
//	console.log("bind 4 called");
	$(window)
		// Bind a click event to hide all visible menus when the document is clicked
		.bind('click.mMenu', function(evt){
				var ul = $(evt.target).closest('.mMenu:visible');
				if (ul.length == 0)
				{
					$('.mMenu:visible').mMenuHide();
				}
		});
})(jQuery);

