$(document).ready(function() {
    var DEBUG = location.href.match(/bfenster/);

    $.fn.tag = function() {
	return this[0] ? this[0].tagName.toLowerCase() : null;
    };
    $.fn.smartnav = function(options) {
	if (options == null)
	    options = {};

	// Hide the outer menu:
	$(this).hide();

	var here = new String(document.location);
	var isMatch = function(possibility) {
	    possibility = normalizeUrl(possibility);

	    // NB: here is a full URL like http://www.bu.edu/section/page.html
	    // possibility is a full URL like http://www.bu.edu/section/
	    
	    // A match occurs when "possibility" is the beginning of the
	    // full URL (or possibly a complete match).
	    
	    return (possibility == here.substring(0, possibility.length));
	};
	var normalizeUrl = function(href) {
	    href = href.replace(/#.*$/, '');
	    href = href.replace(/\?.*$/, '');
	    href = href.replace(/index\.(php|s?html?)$/, '');

	    //href = href.replace(/index\.html$/, '');
	    
	    return href;
	};
	
	var score = function(element) {
	    var url = element.href;

	    var result = 0 + (url.replace(/[^\/]/g, '')).length;
	    if (!url.match(/index\.(php|(s?html))$/))
		result++;

	    // Now, it's possible we have two different links to the
	    // same page in two different Primary Navigation menus.
	    // If so, we should prefer the one with the same parent
	    // directory (e.g., /site/about/ is the parent of
	    // /site/about/blah.html).  So...

	    // Find the parent element, and get its URL:
	    var jqueryElement = $(element).parents("li:last").children("a:first");
	    var parentUrl = normalizeUrl(jqueryElement[0].href);

	    // It's possible (in sidenav) for the parent to link to a
	    // specific page, and not just a directory.  Trim off any
	    // filename at the end, leaving only the directory.
	    parentUrl = parentUrl.replace(/[^\/]+\.[^\/]+$/, '');

	    // Now, if it's a DIFFERENT directory, lower the score by one point.
	    if (normalizeUrl(url).substring(0, parentUrl.length) != parentUrl)
		result -= 1;

	    return result;
	}


	var anchorClassName = options.anchorClassName ? options.anchorClassName : 'activelink';
	var listClassName = options.listClassName ? options.listClassName : 'active';
	var showLists = (typeof(options.showLists) != 'undefined') ? options.showLists : true;

	var highlight = function(match) {
	    $(match).addClass(anchorClassName);

	    $(match).parents("ol:not(.smartnav-ignore), ul:not(.smartnav-ignore), li:not(.smartnav-ignore)").each(function() { 
		if (showLists)
		    $(this).show().addClass(listClassName); 
		else
		    $(this).addClass(listClassName);
		$(this).prev("a").addClass(anchorClassName);
	    });
	    
	    if (showLists) {
		// Show one level of children BELOW this, in case what we're viewing is a parent node with subnav:
		$(match).parent("li").children("ol, ul").show();
	    }
	}


	// HIDE STUFF:

	// Hide all submenus:
	if (showLists)
	    $(this).find("ul,ol").hide().css('display', 'none');
	
	// NB: If we add .css('display', 'none') the thing works fine.
	// If we don't, it breaks in Safari 3.  What the deuce?

	// If we're in a container div of some kind (i.e., .smartnav()
	// was called from something other than the <ul> or <ol>),
	// then show the top-most ul (if you're using ordered lists,
	// just invoke .smartnav() on the right darn element)
	if ($(this).tag() != 'ul' && $(this).tag() != 'ol')
	    $(this).find("ul:first").show();

	here = normalizeUrl(here);


	// FIND CANDIDATE MATCHES:
	var matches = [];
	$(this).find("a:not(.smartnav-ignore)").each(function() {
	    if (isMatch( this.href )) // this.href should be the fully qualified URL
		matches.push(this);
	});

	// HIGHLIGHT THE BEST MATCH:
	if (matches.length == 0) {
	    // No links anywhere that match this page.  Let's at least
	    // show the menu itself.
	} else if (matches.length == 1) {
	    // Yay; only one match.  Let's highlight the bugger:
	    highlight(matches[0]);
	} else if (matches.length > 1) {
	    // Smeg.  Many matches.  Now we need to figure out which one to choose.

	    var bestScore = -1;
	    var bestMatch = null;
	    for(var i = 0; i < matches.length; i++) {
		var s = score(matches[i]);
		if (s > bestScore) {
		    bestScore = s;
		    bestMatch = matches[i];
		}
	    }

	    highlight(bestMatch);
	}

	$(this).show();
    };

    $(".smartnav").each(function() { $(this).smartnav(); });
    $(".smartnav-pnb").each(function() { $(this).smartnav( {showLists: false} ); });

    // if ($("#contentnav").length > 0)
    // 	$("#contentnav")[0].style.display = null;


    $.fn.autowidth = function(options) {
	// if (!DEBUG)
	//     return;

	var menu = this;
	$(this).children("li").each(function() {
	    // These are the PARENT li's
	    if ($(this).children("ul").length == 0)
		return;

	    var width = $(this).width();
	    $(this).children("ul").show();
	    var childWidth = $(this).children("ul").width();
	    if (childWidth < width)
		$(this).children("ul").width(width + 10);

	    // We need the display property to be excluded from the
	    // style="" attribute completely, since otherwise display:
	    // none takes precedence over the stylesheet, which is bad
	    // if ($(this).children("ul")[0].style != undefined)
	    $(this).children("ul")[0].style.display = '';
	});


	return;

	if (!options)
	    options = {};

	$("body").append('<div id="autowidth-placeholder" style="display: inline; line-height: 1; visibility: visible; padding: 0; font-size: 1em;">M</div>');

	var obj = $(this).find("ul > li > a");

	$("#autowidth-placeholder").css("font-family", $(obj).css("font-family"));
	$("#autowidth-placeholder").css("font-size", $(obj).css("font-size"));
	// alert($("#autowidth-placeholder").css("background-color"));
	// foobar();
	// $("#autowidth-placeholder").css("color", $("#autowidth-placeholder").css("background-color") );

	var fontSize = $("#autowidth-placeholder")[0].offsetHeight;
	fontSize = 13;
	// alert($("body").css('font-size'));

	var firstTime = 0;
	$(this).children("li").each(function() {
	    var length = 0;

	    $(this).children("ul").children("li").children("a").each(function() {
		$("#autowidth-placeholder").text( $(this).text() );
		

		// var myLength = $(this).text().length;
		myLength = $("#autowidth-placeholder").width();

		if (myLength > length)
		    length = myLength;
	    });

	    if (DEBUG) {
		length = 0;

		// There's supposed to be only one child ul here (since we're in an EACH loop)
		$(this).children("ul").each(function() {

		    // $(this).show();
		    
		    $(this).children("li").children("a").each(function() {
			var myLength = $(this).width();

			if (myLength > length)
			    length = myLength;
		    });

		    // $(this).hide();
		});
	    }


	    var padding = options.padding ? options.padding : 20;

	    length += padding;
	    
	    if (length < $(this).width())
		length = $(this).width() + 10;

	    // if (length > $(this).width() * 2)
	    // 	length *= 0.7;

	    // $(this).children("ul").width((length / fontSize) + "em")
	    // $(this).children("ul").width(length + "px");
	});

	$("#autowidth-placeholder").remove();
    };

    $(".autowidth").autowidth();
});
