﻿/*

This work is licensed under the Creative Commons Attribution-Share Alike 2.5 Australia License. 
To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/2.5/au/ 

Author: Chad Tolkien - info@sodacreative.com.au
Company: SODA Creative - http://www.sodacreative.com.au
Revision: 1.0
Date: 15/02/2010

Known issues: 
    - Bug if a page url contains the URL of another page.

*/

(function($) {
    $.fn.SelectedNav = function(options) {

        options = $.extend({
            position: 0,  // this sets the position of the 'home' nav option. If no matches are found, we highlight the anchor at this index.
            className: "selected", // this sets the default name of the class to use
            homeHref: "/" // this sets the href for the home/default/index page
        });

        var curUrl = window.location.href;
        curUrl = curUrl.substring(curUrl.lastIndexOf('/'));

        var navEle = $("> li > a[href$=" + curUrl + "]", this); //lets look at the top level anchors for a hit
        if (navEle.size() > 0) {
            navEle.addClass(options.className);
        }
        else { //we didn't find a hit, we have to loop  through
            $("li", this).each(function() {
                var cur = $(this), // current  LI
                    i = $("a", cur), // anchor in LI
                    href = i.attr("href"); // href of anchor
                
                $("ul > li > a", cur).each(function() { // now loop through the child nodes
                    if (CheckURL($(this).attr("href"))) { //if we have a match...
                        AddClass(i); //add the class to the parent anchor
                        return false; // exit the each statement
                    }
                });
            });

        }
        
        function CheckURL(a) {
            if (curUrl == a) {
                return true;
            }
            return false;
        }

        function AddClass(a) {
            a.first().addClass(options.className);
        }
    }

})(jQuery);


