/*******************************************************************************
 jQuery.jMenu
 Copyright (c) 2010 Aporie
 email: contact@aporie.biz

 Licences: MIT, GPL
 http://www.opensource.org/licenses/mit-license.php
 http://www.gnu.org/licenses/gpl.html
 ******************************************************************************/

/*
 * Name:jquery.jmenu
 * Version: 0.1
 * usage : $(selector).jMenu(options);
 */
function parse(obj)
{  var t, s, ok;

	if (typeof obj=="object")
	{
		if (obj.id) s="["+obj.id+"]\n";
		else if (obj.name) s="["+obj.name+"]\n";
		else if (obj.tagName) s="["+obj.tagName+"]\n";
		else if (obj.type) s="["+obj.type+"]\n";
		else s='';
		var attr=Array();

		var exc=arguments[3]?arguments[3].split(';'):null;
		var inc=arguments[2]?arguments[2].split(';'):null;
		var vide=arguments[1]?arguments[1]:false;

		for (var i in obj)
    	{  ok=true;
    		if (exc)
			{	for (var j in exc)
				{	if (i.toLowerCase().indexOf(exc[j].toLowerCase())!=-1)
					{	ok=false;
						break;
					}
				}
				if (!ok) continue;
			}
			if (inc)
			{	ok=false;
				for (var j in inc)
				{	if (i.toLowerCase().indexOf(inc[j].toLowerCase())!=-1)
					{	ok=true;
						break;
					}
				}
				if (!ok) continue;
			}

			ok=vide || ((obj[i]!=null) && (obj[i]!='none') && (obj[i]!='auto') && (obj[i]!='') && (typeof obj[i]!='undefined'))
			if (!ok) continue;

			t=''+obj[i]+'';
			//alert(t+'='+t.indexOf("[native code]"));
			if (t.indexOf("[native code]") == -1) attr.push(i+'="'+t+'"');
		}
		attr.sort();
		for (var i=0; i<attr.length;i++)
			s+=attr[i]+'     /     ';
	}
	else s=obj;

	alert(s);
	return s;
}
(function($) {
$.jMenu = {
	menus:Array(),
	options: {},
	optionsDefault: {
		type : 'tree',
		openEvent : 'click',
		openDelay: 250,
		openAnimate : {effect:[],duration:0},
		openPosition : ['bottom','right'],
		closeEvent : 'click',
		closeDelay: 2000,
		closeAnimate : {effect:['opacity'],duration:250}
	},

	hideMenu : function(level){
	   var m=$.jMenu.menus;
	   var options=$.jMenu.options;
		while(m.length>level)
		{	if(m[m.length-1].attr('visible')!='always')
			{	m[m.length-1].stop(true,true).find('a').data('level',0);
			   if(options.closeAnimate.duration)
				{	ef={}; for(i in options.closeAnimate.effect) ef[options.closeAnimate.effect[i]]='hide';
					m[m.length-1].animate(ef,$.jMenu.options.closeAnimate.duration);
				}
				else m[m.length-1].hide();
				m[m.length-1].data('parent').removeClass('selected');
			}
		   m.pop();
		}
	},

	showMenu : function(current){
	   var level=current.data('level');
	   if($(current).hasClass('selected')) return $(this);

		$.jMenu.hideMenu(level);
		if(level==0) $.jMenu.root=current.parent().parent();
		$.jMenu.options=$.jMenu.root.data('options');
		$(current).addClass('selected');
		$(this).data('parent',current);
		$.jMenu.menus.push($(this));

		$(this).find('a')
			//.css('display','block')
			.data('level',level+1);

		var options=$.jMenu.options;
		var positions=options.openPosition;

		if (level==0 || positions.length<2) p=positions[0]?positions[0]:'bottom';
		else
		{  l=(level%positions.length-1)+1;
		   p=positions[l];
		}
		if($.jMenu.options.type=='pop')
		{	$(this).css('display',''); // Appartion furtive le temps de calculer la hauteur du menu
			switch(p)
			{	case 'right':    //Droite
					t=current.offset().top+($.browser.msie?-2:1);
					l=current.parent().offset().left+current.parent().outerWidth()-($.browser.msie?2:0);
					break;
				case 'left':    //Gauche
					t=current.offset().top+($.browser.msie?-2:1);
					l=current.parent().offset().left-$(this).outerWidth()+($.browser.msie?2:0);
					break;
				case 'top':    //Haut
					t=current.offset().top-$(this).outerHeight()+($.browser.msie?-2:1);
					l=current.offset().left+($.browser.msie?2:0);
					break;
				case 'bottom': 	//Bas
				default:
					t=current.offset().top+($.browser.msie?-2:1)+current.outerHeight();
					l=current.offset().left+($.browser.msie?-2:0);
					break;
			}
			$(this).css('display','none'); // Disparition furtive le temps de calculer la hauteur du menu

			$(this).css({
				  position:"absolute",
		        top:t,
		        left:l
		      });
		}

		$(this).find('a').each(function(index,element){
			$(this).css({display:'block'});
			});

		if(options.openAnimate.duration)
		{	ef={}; for(i in options.openAnimate.effect) ef[options.openAnimate.effect[i]]='show';
			$(this).animate(ef,$.jMenu.options.openAnimate.duration);
		}
		else $(this).show();

		if(options.type=='pop')
		{
			// Fermeture par clic hors du menu
			$(document).bind('click.jMenu',function(){
				$.jMenu.hideMenu(0);
				$(document).unbind('click.jMenu');
			});

	 		// Fermeture par souris hors du menu
			if(options.closeEvent=='mouseover')
			{	$(document).bind('mouseover.jMenu',function(){
					$.jMenu.timer=setTimeout(function(){
						$.jMenu.hideMenu(0);
						$(document).unbind('mouseover.jMenu');
					},$.jMenu.options.closeDelay);
				});
				$.jMenu.root.bind('mouseover.document',function(){
					clearTimeout($.jMenu.timer);
					$(this).unbind('mouseover.document');
				});
			}
		}
		
		return $(this);
	},

   jMenu : function(options){
		return $(this).each(function(){
			var opt = {};
			$.extend (opt, $.jMenu.optionsDefault);
			$.extend (opt, options);
			$(this).data('options',opt);
			$.jMenu.options=opt;

			// Arrête la propagation du mouseover (pour gérer la fermeture par mouseover)
			$(this).bind('mouseover',function(event){
				event.stopPropagation();
	      });

			// Menus
			$(this).find("div").each(function(index,element){
			   if(index)
				{	$(this).hide();
					if($.jMenu.options.type=='pop')
						$(this).css("position","absolute");
				}
				else $(this).addClass('main');
			});

			// Eléments des menus
			$(this).find('a').each(function(index,element){
				$(this).data('level',0);
				if ($(this).attr('href')) $(this).attr('link',$(this).attr('href')).removeAttr('href');

				// Menus sans lien
				if($(this).hasClass('disabled') || ($(this).attr('menu')=='' && $(this).attr('href')==''))
				{   $(this).css({'cursor':'default'});
				}
				// Menus actifs
				else
				{	$(this).css({'cursor':'pointer'});
				
					if($.jMenu.options.type=='tree')
					{	if($(this).attr('menu'))
						{  var sm=$('#'+$(this).attr('menu'));
							var d=sm.attr('duplicate'); d=d?d:0; 
 							$(this).attr('menu',$(this).attr('menu')+'_'+d);
							$(this).append(sm.clone(true).attr('id',$(this).attr('menu')));
							sm.attr('duplicate',d+1);
							var sm=$('#'+$(this).attr('menu'));
							if(sm.attr('visible')=='always') sm.addClass('selected').show();
						}
					}
				   // Fonction d'ouverture du menu
				   fn_openmenu=function(event){
					   var id=$(this).attr('menu');
					   var self=$(this);
						$.jMenu.timer=setTimeout(function(){
							$('#'+id).showMenu(self);
				      },$.jMenu.options.openDelay);
				      event.stopPropagation();
					};
					// Fonction d'appel du lien
					fn_gotolink=function(event){
						document.location=$(this).attr('link');
				      event.stopPropagation();
					};
					// Fonction fermeture des autres menus
					fn_closeother=function(event){
						$.jMenu.hideMenu($(this).data('level'));
						event.stopPropagation();
	            };

					switch($.jMenu.options.openEvent)
					{	case 'mouseover' :		// Ouverture sur entrée souris
						 	// mouseover
							if($(this).attr('menu'))
							{  $(this)
								.bind('mouseover',fn_openmenu)
								.bind('mouseout',function(event){
									clearTimeout($.jMenu.timer);
								});
							}
							else
							{  $(this).bind('mouseover',fn_closeother);
							}
							// click
							if($(this).attr('link'))
							{  $(this).bind('click',fn_gotolink);
							}
							else $(this).bind('click',fn_openmenu);
							break;
						case 'click':			// Ouverture sur clic
						default:
							// mouseover
							$(this).bind('mouseover',fn_closeother);
							// click
							if($(this).attr('menu'))
							{  $(this).bind('click',fn_openmenu);
							}
							else if($(this).attr('link'))
							{  $(this).bind('click',fn_gotolink);
							}
					}
				}
	  		});
  		});
	}
};
$.fn.jMenu = $.jMenu.jMenu;
$.fn.showMenu = $.jMenu.showMenu;
})(jQuery);
