jQuery(function($) {

    // activate the homepage carousel

    $('#mycarousel').jcarousel();

    // activate the selectboxes
    $('select.selectbox').selectbox({
        onChangeCallback: function(args) {
            if (args.selectedVal)
                window.location.href = args.selectedVal;
        }
    });

    // patch around IE's broken hover behavior
    if (window.attachEvent) {
        $("#nav>li").each(function() {
            this.onmouseover = function() {
                this.className += " sfhover";
            }
            this.onmouseout = function() {
                this.className = this.className.replace(new RegExp(" sfhover\\b"), "");
            }
        });
    }

    // tag main nav too close to the right edge
    var width = $("#nav").outerWidth();
    $("#nav>li").filter(function(i) {
        var pos = $(this).position();
        var childWith = $(this).children("ul").outerWidth();
        
        //alert("width: " + width + "pos left: " + pos.left + "Cw:" + childWith);
        
        return width - pos.left < childWith;

    }).addClass("right-side");

    // split tertiary nav lists into two columns, where the size of the links allows
    $("#nav li.sn").each(function() {
        // get width of sublist
        var $sublist = $(this).children("ul.tn");
        var childWidth = $sublist.outerWidth();

        // find max width of links in sublist
        var maxLinkWidth = 0;
        $sublist.find("li.tn > a").each(function() {
            var linkWidth = $(this).outerWidth();
            maxLinkWidth = (linkWidth > maxLinkWidth) ? linkWidth : maxLinkWidth;
        });

        // if less than half list's width, split sublist into two halves
        if (maxLinkWidth <= (childWidth - 15) / 2) {
            var $items = $sublist.children("li");
            var $clone = $sublist.addClass("half").clone();
            var split = Math.ceil($items.length / 2);

            $items.slice(split).remove();
            $clone.children("li").slice(0, split).remove();
            $sublist.after($clone);
        }
    });

    // Store Browse by topic tabs
    if ($(".tabs").length > 0)
      $(".tabs").tabs();

    $('#dialog_link, ul#icons li').hover(
     function() { $(this).addClass('ui-state-hover'); },
     function() { $(this).removeClass('ui-state-hover'); }
    );
});


