/**
 * @author onelson@gmail.com
 */
(function($) {
	$.fn.oMenu = function(o) {
		o = $.extend({
			navigation: false,
			duration : 250,
			durationUp : null,
			easing : 'linear',
			easingUp : null,
			sectionClass : 'section',
			defaultClass : null,
			activeClass : 'active',
			currentClass : 'current',
			panelHeight : false,
			animated : false
		}, o);
		function activate($sec){
			$sec.addClass(o.activeClass);
			if(o.panelHeight)
			{
				$sec.next().animate({'height': o.panelHeight+'px'}, o.duration, o.easing).fadeIn();
			} else if (o.animated) {
				$sec.next().slideDown(o.duration, o.easing);	
			} else {
				$sec.next().show(o.duration);	
			}
			
		}
		function deactivate($sec){
			$sec.removeClass(o.activeClass);
			if(o.panelHeight)
			{
				$sec.next().hide(0);
			} else if (o.animated) { 
				$sec.next().slideUp(o.durationUp ? o.durationUp : o.duration, o.easingUp ? o.easingUp : o.easing);
			} else {
				$sec.next().hide(o.durationUp ? o.durationUp : o.duration);	
			}
		}
		function togglePane($toShow, $toHide) {
			if ($toHide.length != 0){
				deactivate($toHide);
				if(o.animated){
					setTimeout(function(){
						activate($toShow);
					}, o.durationUp ? o.durationUp : o.duration);	
				} else {
					activate($toShow);
				}
			} else {
				activate($toShow);
			}
			
		}
		return this.each(function(){
			$sections = $(this).find('.'+o.sectionClass);

			if(o.navigation){
				
				var url = location.href;
				url = url.replace('#'+location.hash, ''); // we want to match the base document and ignore the hash if present

				var $current = $(this).find("a").filter(function() { return this.href == url; });
				if($current.is('.'+o.sectionClass)){
					$pref = $current;
				} else {
					$pref = $current.parent().parent().prev();
				}
				$current.after('<span class="'+o.currentClass+'">'+$current.text()+'<\/span>').remove();
				
			} else {
				$pref = $sections.parent().parent().find(o.defaultClass ? '.'+o.defaultClass : '.'+o.activeClass);	
			}
			if($pref.length == 0){
				$pref = $sections.eq(0);
			}
			$pref.addClass(o.defaultClass).addClass(o.activeClass);
			$sections.not($pref).next().css('display', 'none');
			$sections.click(function(){
				if($(this).is('.'+o.activeClass) || ($(this).next().length == 0)){
					return true;
				} else {
					$toShow = $(this);
					$toHide = $(this).parent().parent().find('.'+o.activeClass);
					togglePane($toShow, $toHide);
					return false;
				}
			});
		});
	}
})(jQuery);