// breadcrumb utilities jQuery plugin



jQuery.fn.appendBreadCrumbList = function (docRoot, options) {

	// adapted from script by Justin Whitford
	// http://www.webreference.com/js/scripts/breadcrumbs/

	var jqOutputTarget = $(this);

	// establish function settings (can be overridden by passing options to this function)
	var settings = jQuery.extend({
		docRoot:		docRoot
		, docRootLabel:	"Home"
		, delimAfter:	"&gt;"
		, labels:		{ }
	}, options);

	var sThisURL = location.href;
	var sThisPath = sThisURL.slice(sThisURL.indexOf("/", sThisURL.indexOf("//") + 2));
	sThisPath = sThisPath.replace(new RegExp("^" + settings.docRoot), "/");
	var aSegments = sThisPath.slice(1).split("/");
	var bIsIndexPage = (aSegments.slice(-1)[0] == "" || aSegments.slice(-1)[0].charAt(0) == "?" || aSegments.slice(-1)[0].indexOf("index") >= 0);
	var aSteps = ['<a href="' + settings.docRoot + '">' + settings.docRootLabel + '</a>'];
	var sLink;
	
	// build array of steps
	for (var i = 0; i < aSegments.length - 1; i++) {
		sLink = '<a href="';
		for (j = 2; j <= aSegments.length - i; j++) sLink += '../';
		sLink += aSegments[i] + '/">' + labelize(aSegments[i]) + '</a>';
		aSteps.push(sLink);
	}
	
	// sequence steps semantically as nested single-item lists
	var nFinalStepIndex = aSteps.length - ((!bIsIndexPage) ? 1 : 2);
	for (var i = nFinalStepIndex; i >= 0; i--) {
		if (i == nFinalStepIndex) {
			if (jqOutputTarget.get(0).tagName.toLowerCase() == "ul")
				jqOutputTarget.append("<li>" + aSteps[i] + settings.delimAfter + "</li>");
			else
				jqOutputTarget.html("<ul><li>" + aSteps[i] + settings.delimAfter + "</li></ul>");
		} else {
			jqOutputTarget.children(":first-child").wrap("<ul><li></li></ul>").before(aSteps[i] + settings.delimAfter);
		}
	}



	function labelize (dirName) {
		var label;
		if (settings.labels[dirName]) {
			// use label for directory name if specified;
			label = settings.labels[dirName];
		} else {
			// ... otherwise, use directory name (w/spaces, capitalized)
			label = dirName;
			label = label.replace(/[_-]/g, " ");
			label = label.replace(/\b(\w)/g, function (w, p1) {return p1.toUpperCase();});
		}
		return label;
	}

};



jQuery.fn.indicateCurrentPage = function (classToAdd, innermostOnly) {

	var jqOutputTarget = $(this);

	// indicate current page
	var sCurrentHref = (location.pathname.replace(/index.[^.]+$/, '')).replace(/%2D/gi, '-');
	var sMenuHref;
	jqOutputTarget.each(function(){
		sMenuHref = $(this).find("> a").attr("href");
		if (sCurrentHref == sMenuHref) $(this).addClass(classToAdd).parents("li").addClass(classToAdd);
	});
	if (innermostOnly == true) {
		jqOutputTarget.each(function(){
			if ($(this).find("." + classToAdd).length > 0) $(this).removeClass(classToAdd);
		});
	}

};
