/**
 * Provides basic tree behavior and styling.  
 * 
 * Author : vasile.orza
 * 
 *
 * Usage example: 
 * 	$("#myTree").tree();
 * 
 * 	<ul id="myTree">
 *  	<li>
 *  		<a>node1</a>
 *  		<ul>
 *  			<li>
 *  				<a>leaf1</a>
 *  			</li>
 *  			<li>
 *  				<a>leaf2</a>
 *  			</li>
 * 			</ul>
 *  	</li>
 *  	<li>
 *  		<a>leaf3</a>
 *  	</li>
 * 	</ul>
 * 
 */
(function($){
	var defaults = {
			singleExpand: true
	};

	$.fn.tree = function(userOptions) {
		var options = $.extend({}, defaults, userOptions);

		return this.each(function() {
			// tree styling & dynamic behavior
			var $root = $(this);
			$root.addClass("treeRoot")
					.find("ul").hide().end()
					.find("li").not(":has(ul)").addClass("leaf").end()
								.has("ul").addClass("node").addClass("expandable")
              								.prepend($("<span>").html("+").addClass("expand"))
              								.prepend($("<span>").html("-").addClass("collapse")).end().end()
    				.find(".expand, .collapse").click(function() {
    					$(this).parent().toggleClass("expandable").toggleClass("collapsable")
    									.children("ul").toggle("normal");
    				});

			// 'single expand' behavior - collapse siblings on node expansion
			if (options.singleExpand) {
				$root.find(".expand").click(function() {
					$(this).parent().siblings(".collapsable").addClass("expandable").removeClass("collapsable selected")
																.children("ul").hide("normal");
				});
			}

			// set as selected the nodes having the same URL and request parameters as the current page
			var $selectedLinks = $root.find("a").filter(function() {
				if (window.location.pathname.indexOf(this.pathname) < 0) {
					return false;
				}
				if (this.search) {
					var paramList = this.search.slice(1).split("&");
					for (index in paramList) {
						var param = paramList[index];

						var paramPattern = new RegExp("(^|&|\\?)" + param + "(&|$)");
						if (!paramPattern.test(window.location.search)) {
							return false;
						}
					}
				}
				return true;
			});

			$selectedLinks.parent().addClass("selected")
									.parents(".node").children(".expand").click();
		});
	};
}) (jQuery)

