/**
JavaScript to complement Messiah Studio coding idioms.
*/


(function()
{
    /**
    Navigation expanding/highlighting.

    Expects HTML in the following format:

    <ul id="navigation">
        <li>
            <a href="/">Home</a>
        </li>
        <li>
            <a href="/about/">About Us</a>
            <ul>
                <li>
                    <a href="/about/beliefs/">Our Beliefs</a>
                </li>
                <li>
                    <a href="/about/faq/">Frequently Asked Questions</a>
                </li>
            </ul>
        </li>
        <li>
            <a href="/contact/">Contact us</a>
        </li>
    </ul>
    */

    function init()
    {
        // Add class 'selected' to links to current page
        mylinks = jQuery('#navigation a');
        mylinks.each(selectedIfCurrent);

        // Hide all 'inner' navigation lists
        innerLists = jQuery('#navigation > li > ul');
        innerLists.each(hide);

        // Show 'inner' lists if link for current page
        innerLists.each(showIfCurrent);
    }

    function selectedIfCurrent()
    {
        pathname = this.pathname
        if( ! RegExp('^/{1}').test(pathname) )
            pathname = '/'+pathname;

        // Homepage
        if(window.location.pathname == '/' && pathname == '/')
        {
            jQuery(this).addClass('selected');
            return false;
        }

        pattern = RegExp('^'+pathname);
        if(pattern.test(window.location.pathname) && pathname != '/')
        {
            jQuery(this).addClass('selected');
        }
    }

    function hide()
    {
        jQuery(this).css('display', 'none');
    }

    function showIfCurrent()
    {
        // Skip homepage
        if(window.location.pathname == '/')
            return;

        // Check links inside our list
        mylist = jQuery(this);
        anchors = mylist.find('a');
        link_found = false;
        pattern = RegExp('^'+window.location.pathname);
        for(i=0; i<anchors.length; i++)
        {
            a = anchors[i];
            pathname = a.pathname;
            if( ! RegExp('^/{1}').test(pathname) )
                pathname = '/'+pathname;

            if(pattern.test(pathname))
                mylist.css('display', 'inline');

            //alert(a.pathname + ' -> ' + window.location.pathname);
        }
    }

    // Initialisation -- have init() run once page has finished loading
    jQuery(document).ready( init );

})();




