(function($) {
  	$.fn.threeTierNav = function(options) {
    	debug("starting 3tier menu");
    	
		// build main options before element iteration
    	var opts = $.extend({}, $.fn.threeTierNav.defaults, options);
                         
		// iterate and reformat each matched element
    	return this.each(function() {
			// get this reference for functions
			$3tier = $(this);                   
			
			// open levels if there is initial state
			$("#firstLevel_open", $3tier).show();
			$("#secondLevel_open", $3tier).show();

			// show plus signs on all expandable
			var $setOfFirstLevelExpandable = $("> li:has(ul) > a", $3tier);
			$setOfFirstLevelExpandable.addClass("expandable");

			// show plus signs on all expandable
			var $setOfSecondLevelExpandable = $("ul > li:has(ul) > a", $3tier);
			$setOfSecondLevelExpandable.addClass("expandable");

			// add expanded class to open levels if there is initial state
			$("#firstLevel_open", $3tier).prev().attr("class","expanded");   
			$("#secondLevel_open", $3tier).prev().attr("class","expanded");   

			// first level event handlers
			$setOfFirstLevelExpandable.click(function(e){  
				var $thisNav = $(this).parent().parent();  
				
				// close any second level old one and clear the id, change class to expandable
				$("#secondLevel_open", $thisNav).slideToggle().attr("id","").prev().attr("class","expandable");		

				// close the old one, change class to expandable
		        var $oldOpen = $("#firstLevel_open", $thisNav);
				$oldOpen.slideToggle();    
				$oldOpen.prev().attr("class","expandable");		

				// open this one
				var $newOpen = $(this).next();
				if($oldOpen.attr("id") != $newOpen.attr("id")) { // if not clicking the same link... 
					$newOpen.slideToggle();
					$newOpen.attr("id","firstLevel_open");                                    
					$newOpen.prev().attr("class","expanded");
				}
				$oldOpen.attr("id",""); // old <ul> is closed, clear the id

				// prevent from going to the href
				e.preventDefault();
			});

			// second level
			$setOfSecondLevelExpandable.click(function(e){
				var $thisNav = $(this).parent().parent().parent();  
				
				// close the old one at that level, if exists
		        var $oldOpen = $("#secondLevel_open", $thisNav);
				$oldOpen.slideToggle();
				$oldOpen.prev().attr("class","expandable");		

				// open the one we clicked
				var $newOpen = $(this).next();
				if($oldOpen.attr("id") != $newOpen.attr("id")) { // if not clicking the same link... why doesn't it work?
					$newOpen.slideToggle();
					$newOpen.attr("id","secondLevel_open");
					$newOpen.prev().attr("class","expanded");
				}
				$oldOpen.attr("id",""); // old <ul> is closed, clear the id

				e.preventDefault();
			});   
			
	    });
  	};  

  	function debug(message) {
    	if (window.console && window.console.log)
      		window.console.log(message);
  	};
})(jQuery); 
