//  jquery.bkj.highlightNav.js
//
//  Usage:  Call on a the main UL object of a nav.  The code will find a descendant A tag
//   that has an href which matches the end of the current URL.
//
//  Warning: untested with relative hrefs.
//
//  Options:
//    highlightClass - the class to give to the LI containing the A tag that links to the current page.
//		Default is 'current'.
//    highlightAncestorClass - the class to give to every LI above the current LI. Default is 'current-ancestor'.
//    topLevelOnly - whether or not to only give the current class to the top most LI. Defaults
//			to 'false'.  if set to true, highlightAncestorClass isn't used.
//
//  Examples:
//		$('ul.sf-menu').highlightNav();
//
//		OR
//
//		$('ul.sf-menu').highlightNav({
//			topLevelOnly: true,
//			highlightClass: 'highlighted'
//		});
//
//		OR
//
//		$('ul.sf-menu').highlightNav({
//			highlightClass: 'highlighted',
//			highlightAncestorClass: 'parent'
//		});



(function($) {
  
	$.fn.highlightNav = function(options) {
		// Extend our default options with those provided.
		// Note that the first arg to extend is an empty object -
		// this is to keep from overriding our "defaults" object.
		var opts = $.extend({}, $.fn.highlightNav.defaults, options);
		
		var root = $(this);
		var current = null;

		function basenameAndSanitize(path) {
			return path.replace(/\\/g,'/').replace( /.*\//, '' ).replace(/\?/g, '\\?');
		}

		root.find('li a').each( function() {
			var a = $(this);
			
			var hrefRegex = new RegExp( basenameAndSanitize(window.location.href) + '$', 'i');
			
			if (a.attr('href').match(hrefRegex)) {
				current = a;
				return false; // break out of the .each()
			}	
		});
		
		if (current) {
			if (opts.topLevelOnly) {
				current.parents('li').addClass(opts.highlightAncestorClass);
				root.children('.' + opts.highlightAncestorClass).addClass(opts.highlightClass);
				$('.' + opts.highlightAncestorClass).removeClass(opts.highlightAncestorClass);
			} else {
				var li = current.closest('li');
				li.addClass(opts.highlightClass);
				li.parents('li').addClass(opts.highlightAncestorClass);
			}
		}
	}
	
	$.fn.highlightNav.defaults = {
		topLevelOnly: false,
		highlightClass: 'current',
		highlightAncestorClass: 'current-ancestor'
	}
	
})(jQuery);

