/* for left menus */

(function($){
	$.fn.left_menu = function(opts){
		var 
			$obj = $(this),
			defaults = {
				link_callback : function(){},
				sublink_callback : function(){}
			},
			settings = $.extend(defaults,opts);
		
		$obj.each(function(){
			var 
				$menu = $(this).find('ul.menu_items'),
				$links = $menu.children('li').children('h1,h2,h3,h4,h5,h6'),
				$sublinks = $menu.find('ul.subitems');
			
			$sublinks.show().each(function(){
				var 
					$ul = $(this),
					height = $ul.height();

				$ul.data('originalHeight',height);
			}).hide();
			
			$links.click(function(){
				var 
					$this = $(this),
					$parent_li = $(this).parent();
				
				if( $parent_li.hasClass('current') ){
					return false;
				}
				
				var 
					$to_show = $this.siblings('ul.subitems'),
					$to_hide = $menu.find('ul.subitems').not( $to_show );
				
				//for changing the states
				$links.parent().removeClass('current');
				$parent_li.addClass('current');

				if($to_show.length){
					$sublinks.find('li').removeClass('current');
					$to_show.find('li:eq(0)').addClass('current');
				}
				
				$to_show.css({'height':0}).animate({'height':$to_show.data('originalHeight')});
				
				$to_hide.filter(':visible').each(function(){
					var 
						$this = $(this),
						orig = {
							padding_top : $this.css('paddingTop'),
							padding_bottom : $this.css('paddingBottom')
						};
					
					
					$this.animate({'height':0,'paddingTop':0,'paddingBottom':0},{
						complete:function(){
							$(this).hide().css({
								'height':'',
								'paddingTop':orig.padding_top,
								'paddingBottom':orig.padding_bottom
							});
						}
					});
				});
				
				settings.link_callback.call( $this );
			});
			
			$sublinks.children('li').click(function(){
				var
					$this = $(this);

				if($this.hasClass('current')){
					return false;
				}

				$sublinks.find('li').removeClass('current');
				$this.addClass('current');			
				settings.sublink_callback.call( $this );
			});
			
			//so when it init's the first is .current
			$links.eq(0).parent().addClass('current');	
			
		});
		
		return $obj;
	}
})(jQuery);
