(function($)
{
	
	$.fn.slideMenu = function(options) 
	{
		if(!options.menuHeight) 	options.menuHeight = parseInt($("#subMenu").css('height')); //sets height of open menu
		if(!options.slideSpeed)		options.slideSpeed = 500; //sets speed of open effect
		if(!options.fadeSpeed) 		options.fadeSpeed = 300; //sets speed of fade effect
		if(!options.delimeter) 		options.delimeter = '-'; //sets the list delimeter
		if(!options.hoverClass) 	options.hoverClass = 'li_hover'; //sets the hover class for the list tags
		if(!options.onClass) 		options.onClass = 'li_on'; //sets the on class for the list tags
		if(!options.anchorHoverClass) 	options.anchorHoverClass = 'a_hover'; //sets the hover class for anchor tags
		if(!options.anchorOnClass) 		options.anchorOnClass = 'a_on'; //sets the on class for anchor tags
		if(!options.cookie) 		options.cookie = true; //use cookies to save the state of the menu from one page to another
		
		$("#subMenu").css({height:options.menuHeight+"px"});
	//	$("#slideMenu ul.tiered").css({height:(options.menuHeight-10)+"px"});
		
		var hovered = false;
		var ajarray = {};
		var slideMenuOpen = false;
		var lastTab = null;
		var a = {};
		
		var slideMenuClosed = function(){
			slideMenuOpen = false;
			$("#subMenu").SlideOutUp(options.slideSpeed);
		};
		
		var openMenu = function(element)
		{
		//	console.log("THE ELEMENT IS: "+element+ "THE HTML IN:" + $("#"+element).html() + "END HTML IN")
			if($("#"+element).html()==null)
			{
				
				var p = {};
				//the element isn't loaded yet.. load it.
				createList(element);
				var split = element.split('_');
				p['table'] = split[0];
				p['id'] = split[1];
				//alert(p['table']);
				$.ajax({ 
					type: "POST",
	                url: '/index.php/management/ajax_load_menu',
					dataType: "html",
					data: p, 
					async: false,
	                success: function(str) { 
					
					ajarray[element] = str;
					
				//	alert(parent_id)
					//	if(parent_id.match(/d_/)!=null) $("#"+parent_id).prepend(str);
						//else $("#"+parent_id).after(str);
						var msg_split = str.split('SPLITMEHERE');
						
						if(msg_split[1]) $("#"+element).after(msg_split[1]);
						$("#"+element).html(msg_split[0]).css({display:'block'});
						
						
						finishOpen(element);
				    } 
	        	}); 
				
			}
			else
			{
				finishOpen(element)
			}
			
			
		};
		
		var createList= function(element)
		{
				var parent = $("#l-"+element).parent();
				var parent_id = parent.attr('id');
				
				if(parent_id=='m1')
				{
					parent_id = 'd_'+element;
						
				}
				
				if(parent_id.match(/d_/)!=null) $("#"+parent_id).prepend('<ul class="tiered" id="'+element+'"></ul>');
				else $("#"+parent_id).after('<ul class="tiered" id="'+element+'"></ul>');
		}
		
		var finishOpen = function(element)
		{
			slideOpen('.tiered li');
		//	$("#"+element+":hidden").SlideInLeft(options.slideSpeed,function(){
				
				$("#"+element).css({overflow:'auto',display:'block'});
			//});
			
	
			//console.log(element);
			//console.log("HTML:" + $("#"+element).html() + "END HTML")
		}
		
		var slideOpen = function(element)
		{
			$(element).unbind();
			
			
			$(element).mouseover(function(){
				if($(this).children('a').html()!=null) $(this).addClass(options.anchorHoverClass);
				else $(this).addClass(options.hoverClass);
				hovered = true;
			});
			
			$(element).mouseout(function(){
				if($(this).children('a').html()!=null) $(this).removeClass(options.anchorHoverClass);
				else $(this).removeClass(options.hoverClass);
				hovered = false;
			});
			
			$(element).click(function(){
				$(element).parent().children('li').each(function(){
					$(this).removeClass(options.anchorOnClass);
				});
				bindElement(this,false);
			});
		};	
		
		var bindElement = function(emt,cookie)
		{
			
			for(key in ajarray)
			{
				if($("#"+key).html()==null) {
					$("#"+key).html(ajarray[key]);
					//alert(key)
				}
				if($("#"+key).attr('class')==undefined) createList(key);
			}
			
			
			if($(emt).children('a').html()!=null && options.cookie)
				{
					setCookie(emt);
					return true;
				}
				
				var key = $(emt).parent().attr('id');
				var element = stripId($(emt).attr('id'));
				var parent_element = $(emt).parent().attr('id');
				if(cookieRoot!='') var cook = stripId($(cookieRoot).attr('id'));
				
				
				if(a[key]!=null) 
				{
					$(a[key]).removeClass(options.onClass);
					var div = stripId($(a[key]).attr('id'));
				
					if(parent_element=='m1')
					{	
						if(div!=element) 
						{
							$("#d_"+div).hide();
							$("#d_"+element).fadeIn();
						}
						else if(element!=cook) 
						{
							slideMenuClosed();
							slideClosed(key);
							a[key] = null;
						}
						else
						{
							cookieRoot = '';
						}
						
					}
					else
					{
						slideClosed(key);
					}
				}
				else
				{
					$("#d_"+element+":hidden").show();
				}
				
				if(div!=element || element==cook)
				{
					$(emt).addClass(options.onClass);
					
					a[key] = emt;
					if(!slideMenuOpen && !cookie)
					{
						slideMenuOpen = true;
						$("#subMenu").SlideInUp(options.slideSpeed,function(){
							openMenu(element);
						});
					}
					else
					{
						openMenu(element);
					}
				}

		};
		
		var stripId = function(element) {
				element_split = element.split(options.delimeter);
				element = element_split[1];
				return element;
			};
		
		
		var cookieRoot = '';
		var cookieStr = '';
		
		var getCookie = function()
		{
			var savedState = $.cookie('slideMenu');
			
			if(savedState!='' && savedState!=undefined && savedState!=null) //definately some data here
			{
				var steps_split = savedState.split('::');
				
				for(i=0;i<(steps_split.length-1);i++)
				{
					
					if(i!=(steps_split.length-2))
					{
						//
						var emt = document.getElementById(steps_split[i]);
						if(emt)
						{
							var element = stripId(steps_split[i]);
							
							if(i!=0) bindElement(emt,true);
							else 
							{
								openMenu(element);
								var key = $(emt).parent().attr('id');
								a[key] = emt;
								cookieRoot = emt;
							}
						}
					}
					else
					{
						//the last element loaded is the html for the anchor tag, not the list item.  get the previous element id and go through that table for the match
						$("#"+element).children('li').each(function(){
								if($(this).children('a').html() == steps_split[i]) 
								{
									$(this).addClass(options.anchorOnClass);
								}
						});
					}
					
				}
			}	
		};
		
		var setCookie = function(element)
		{
			
			cookieStr = '';
			cookieString(element);
			$.cookie('slideMenu',cookieStr,{ expires: 7, path:'/'});
		};
		
		var cookieString = function(element)
		{
			
			var id = $(element).children('a').html();
			if(id==undefined || id==null) id = $(element).attr('id');
			var parentKey = $(element).parent().attr('id');
			
			if(parentKey!=undefined)
			{
				cookieStr = id + "::" + cookieStr;
				cookieString('#l'+options.delimeter+parentKey);
			}
			
		};
		
		var slideClosed = function(key)
		{
			/* 1. get the class of the a[key] object
			 * 2. use the class to get the a[key] of the child table (equal to the id)
			 * recurse
			 */
			var menuItem = $(a[key]).attr('id');
			var parentKey =  $(a[key]).parent('ul').parent('div').attr('class');
			if(menuItem!=undefined)
			{
				if(parentKey!='base') 
				{
					menuItem = stripId(menuItem);
					$("#"+menuItem+" li").each(function(){
						$(this).removeClass(options.onClass);
					});
					$("#"+menuItem+":visible").css('overflow','hidden').fadeOut(options.fadeSpeed);
					slideClosed(menuItem);		
					a[key] = null;		
				}	
			}
		};
		
			
		
		
		var scrollMenu = function(element)
		{
			
			var target =  $("#"+element);
			margin = parseInt(target.css('marginTop'));
			var listTotalHeight = 0;
			var listHeight = 0;
			var listCount;	
			target.children('li').each(function(i){
				listCount = i;
				height = $(this).height();
				if(height>listHeight) listHeight = height;
			});
			listTotalHeight = listHeight * listCount;
			
			if(listTotalHeight > parseInt(target.css('height')))
			{
				newMargin = margin - 5;
				newHeight = parseInt(target.css('height')) + 5;
				target.css({marginTop: newMargin+"px",height:newHeight+"px"});
				margin = newMargin;
			}
			
		};
		if(options.cookie) getCookie();
		slideOpen('.base ul li');
	};
	
	})(jQuery);
