/* 
SlashC jQuery Two Tier Sliding Menu plugin
hi@slashc.com, www.slashc.com
*/
(function($)
{	
	/* plugin methods */
	var methods =
	{
		/* intialization */
		init : function(autoCls)
		{
			if (typeof autoCls === 'undefined') autoCls = false;
			return this.each(function()
			{
				var mnu = $(this);	// the menu			
				if(!mnu.data('d'))
				{
					var mul = mnu.children('ul').first(); // main list
					var mli, ma; // main item and main anchor
					mul.children('li').has('ul').each(function() // select only items that have a nested list
					{
						mli = $(this); ma = mli.children('a').first();
						var ch = ma.height(), // closed height
						oh = mli.height(), // opened height
						isSel = mli.hasClass('selected'); // check if selected
						mli.css('height', isSel ? oh : ch).data('d', { ignr: false, mul: mul, autoCls: autoCls, cls: isSel ? false : true, ch: ch, oh: oh });
						ma.bind('click.slashcTwoTierMenu', $.proxy(function(e)
						{
							var d = this.data('d'); d.ignr = true; // ingore auto close
							methods._toggleLi(this);
							if (d.autoCls)
							{
								d.mul.children('li').has('ul').each(function()
								{
									var li = $(this), d2 = li.data('d');
									if (!d2.ignr) methods._closeLi(li);
									d2.ignr = false;
								});
							}
							e.preventDefault();
						}, mli));
					});
					mnu.data('d', 'inited');
				}
			});
		},
		/* open item */
		_openLi : function(li)
		{
            /* modifica Laura 2011-09-05 per rimuovere il segnalino */
            $('#menuArea li').removeClass('selected');
            /* fine modifica */
			var d = li.data('d');
			if (d.cls)
			{
				d.cls = false;
				li.stop().animate({ height: d.oh }, 'fast').addClass('selected');
			}
		},
		/* close item */
		_closeLi : function(li)
		{
			var d = li.data('d');
			if (!d.cls)
			{
				d.cls = true;
				li.stop().animate({ height: d.ch }, 'fast').removeClass('selected');
			}
		},
		/* toggle item */
		_toggleLi : function(li)
		{
			var d = li.data('d');
			if (d.cls) methods._openLi(li);
			else methods._closeLi(li);
		}
	};
	
	/* Two Tier Sliding Menu plugin */
	$.fn.slashcTwoTierMenu = function(p1, p2)
	{
		/* p1 - method name, p2 - method options */
		/* p1 - options for init method, p2 - undefined */
		if (typeof p2 === 'undefined')
		{
			if (typeof p1 === 'undefined') return methods.init.call(this);
			else if (methods[p1]) return methods[p1].call(this);
			else return methods.init.call(this, p1);			
		}
		else if (methods[p1])
		{
			if (p2) return methods[p1].call(this, p2);
			else return methods[p1].call(this);
		}
		return this;
	};
	
	/* Attach plugin to all the HTML instances */
	$(document).ready(function()
	{
		$('#menuArea').slashcTwoTierMenu(true);
	});
	
})(jQuery);
