$(document).ready(function() {

    $(".navitem").bind("click", 
        function () {
            var navitem = $(this);
            $(".navitem").removeClass("selected");
            $('#top_border').hide();
            $(".nav_submenu").hide();
            navitem.addClass("selected");
            navitem.blur();
            var submenuid = "#sub" + navitem.attr('id');
            if($(submenuid + " li").length !== 0) {
                $(submenuid).show();
            } else {
                $('#top_border').show();
            }
        }   
    );

    var navitem = $('.navitem:first');
    $('.nav_toplevel .navitem').each( function () {
        var thisnavitem = this;
        $($(this).attr('urls').split(",")).each( function () {
            if(location.pathname.match(new RegExp(this))) {
                navitem = $(thisnavitem);
                return false;
            }
        });
    });

    $(".navitem").removeClass("selected");
    $('#top_border').hide();
    $(".nav_submenu").hide();
    navitem.addClass("selected");
    var submenuid = "#sub" + navitem.attr('id');
    if($(submenuid + " li").length !== 0) {
        $(submenuid).show();
    } else {
        $('#top_border').show();
    }

    var url = location.pathname;
    var maybes = [];
    $(submenuid + " li").each( function() {
            var link = $(this).find("a");
            if(link.length === 0) { return; }
            link = link.attr("href");
            if(link == url.substring(0, link.length)) {
                maybes.push($(this));
            }
    });
    
    var max_length = 0;
    var best_match = null;
    for(var i = 0; i<maybes.length; i++) {
        var link = maybes[i].find("a").attr("href");
        var j = 0;
        for(; j<link.length; j++) { if(url[j] != link[j]) { break; } }
        if(j > max_length) {
            best_match = maybes[i];
        }
    }
    if(best_match !== null)  {
        best_match.addClass('selected');
    }

    $('.accordian_menu').each(function() {
        var me = $(this);
        var active = me.attr('active');
        if(!active) {
            me.accordion( { header : '.menu_head', collapsible : true, active : false, clearStyle : true } );
        } else {
            active = ":nth-child(" + (active*2-1) + ")";
            me.accordion( { header : '.menu_head', active : active, collapsible : true, clearStyle : true } );
        }
    });

    $('#pnb li').mousedown( function() {
        $(this).children().click();
    });

    $('#searchform').submit( function () {
        var url = $(this).attr('action') + "?" + $(this).serialize();
        window.open(url);
        return false;
    });

    $("a[href^='http']").attr('target','_blank');

});
