/* ------------------------------------------------------------
 * PROJECT        : 
 * FILENAME       : jq.buildTreeNav.js
 * ------------------------------------------------------------
 * LAST UPDATED   : 21 Mar 2010
 * ------------------------------------------------------------
 * AUTHOR(S)      : Kevin Scholl (http://www.ksscholl.com/)
 * ------------------------------------------------------------ */

jQuery.fn.buildTreeNav = function(settings) {
	settings = jQuery.extend({
		overallWidth : "auto",
		controlAll   :  true,
		controlAlign : "left",
		initialState : "collapsed"
		}, settings);
	this.each(function() {
		var thisID = $(this).attr("id");
		// set the initial states of the nav tree
		$(this)
		  .addClass("tvn")
		  .css("width",settings.overallWidth)
		  .find("li:not(:has(ul))").css("background-image","url(/images/icon_page.png)").end()
			.find("li:has(ul)")      .append("<div class=\"treeNavControl\">").end()
		
		// expand or collapse individual nav node
			.find("li > div.treeNavControl").click(function() {
				var treeNavControlBg 
					= $(this).parent().find(" > ul").is(":visible") == true 
					? "url(/images/icon_folder_closed.png)" 
					: "url(/images/icon_folder_open.png)";
				$(this).parent().find(" > ul").slideToggle();
				$(this).css("background-image",treeNavControlBg);
				});
		
		// set initial state of tree, collapse or expanded
		if (settings.initialState == "collapsed")
		  $(this).find("ul").css("display","none");
		else
			$(this)
			  .find("div.treeNavControl").css("background-image","url(/images/icon_folder_open.png)").end()
				.find("ul").css("display","block");

		// build expand/collapse all control
		if (settings.controlAll == true) {
			$(this)
			  .before("<div class=\"treeNavControlAll\"></div>\n")
				.prev("div.treeNavControlAll")
				  .css("width",settings.overallWidth == "auto" ? settings.overallWidth : parseInt(settings.overallWidth) + 22 + "px")
				  .append("\n<p style=\"text-align: " + settings.controlAlign + "\"> &nbsp;|&nbsp; </p>\n")
				  .find("p")
						.prepend("<a href=\"#\">Expand All</a>").find("a:contains('Expand')").click(function() {
							$("ul#" + thisID)
								.find("div.treeNavControl")
									.css("background-image","url(/images/icon_folder_open.png)")
									.end()
								.find("ul")
									.css("display","block")
									.end();
							return false;
							}).end() // end Expand All link
						.append("<a href=\"#\">Collapse All</a>").find("a:contains('Collapse')").click(function() {
							$("ul#" + thisID)
								.find("ul")
									.css("display","none")
									.end()
								.find("div.treeNavControl")
									.css("background-image","url(/images/icon_folder_closed.png)")
									.end();
							return false;
							}).end() // end Collapse All link
						.end(); // end paragraph
			}

    });
	};
