/*
 * clones the nav in a far off div, gets height, attaches to real nav, then
 * cleans up. This is to avoid the flash of unprocessed navigation. Now they
 * are all hidden by default.
 */
var nc = $('#navigation > ul').clone(),
    nt = $('#navtest'),
    sections = $('#navigation > ul > li > ul');
nt.append(nc);

// looking at clone for height then adding attribute to real nav section
$('> ul > li > ul', nt).each(function(i) {
    var sel = sections.eq(i),
        tel = $(this);
    tel.show();
    /*
     * The next line can get the opened section a wrong height reading, but it
     * doesn't matter since it is showing and the next animation results in a 
     * link being clicked.
     */
    $('li:first > ul', tel).show();
    if (!sel.hasClass('open'))
    {
        $('li:first > ul', sel).show();
    }
    sel.attr('fixed_height', tel.innerHeight());
});

sections.each(function() {
    var el = $(this);
    if (el.hasClass('open'))
    {
        el.show();
    }
    else
    {
        el.hide().css('opacity', 0.01);
    }
});

nt.remove();

var principals = $('#navigation ul.principals');
if (!principals.hasClass('open'))
{
    principals.hide();
}

$('#navigation > ul > li > span')
    .click(function () {
        var span = $(this),
            next = span.next();
        if (next.css('display') === 'none')
        {
            var old = $('#navigation > ul > li > ul:visible'),
                go = function() 
                    {
                        window.location.replace($('a', this).eq(0).attr('href'));
                    },
                open = function()
                    {
                        next.animate(
                            {
                                height: "show",
                                opacity: 1
                            },
                            500,
                            'easeOutSine',
                            go
                        );
                    };

            if (old.length > 0)
            {
                old.animate(
                    {
                        height: "hide",
                        opacity: 0.01
                    },
                    500,
                    'easeOutCirc',
                    open
                );
            }
            else
            {
                open();
            }
        }
    });

$('#navigation > ul > li a').each(function() {
    var link = $(this);
    if (location.pathname.indexOf(link.attr('href')) === 0)
    {
        link.addClass('current');
        if (link.parent().parent().hasClass('projects'))
        {
            link.parent().addClass('current');
        }
    }
});
